2

Is it possible to make the gradient cells in UICollectionView? I tried this in the ViewController file and nothing happened:

extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return itemMenuArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if let itemCell = collectionView.dequeueReusableCell(withReuseIdentifier: "main_menu_cell", for: indexPath) as? MainWindowCollectionViewCell {

            itemCell.menu = itemMenuArray[indexPath.row]

            let gradientLayer = CAGradientLayer()
            gradientLayer.colors = [UIColor(red: 245/255, green: 78/255, blue: 162/255, alpha: 1.0), UIColor(red: 255/255, green: 118/255, blue: 118/255, alpha: 1.0)]
            gradientLayer.startPoint = CGPoint(x: 0, y: 0)
            gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
            gradientLayer.frame = view.bounds

            itemCell.layer.addSublayer(gradientLayer)

            return itemCell
        }

        return UICollectionViewCell()
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Egor Iskrenkov
  • 433
  • 4
  • 15
  • 1. Get rid of the `if let`. This is a case where you actually do want to use `as!` and force a crash if the cell can't be cast to the custom type. 2. Don't setup the gradient in `cellForItemAt`. That code belongs in the implementation of your custom cell class. 3. Why do you set the gradient layer's frame to be the bounds of the view controller's view instead of the cell's bounds? – rmaddy Jul 20 '18 at 18:43
  • Thank you so much :D I just started building my the very first app and hope to learn Swift better thanks to my mistakes there and StackOverflow. – Egor Iskrenkov Jul 22 '18 at 14:38

0 Answers0