Adrian
Adrian

Reputation: 16725

Adding gradient on background image of UITableViewCell

I have a UITableView inside of a UIViewController. I'm attempting to apply a gradient over a background image in a UITableViewCell. I can get a gradient to draw, but it's drawing a clean line between the colors instead of a gradient.

In my cellForRowAt, I assign an object to my CustomTableViewCell, like so:

  let cellIdentifier = "Cell"
  // all the standard data source, delegate stuff for uitableviews

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! CustomTableViewCell
    let scheduleItem = scheduleData[indexPath.row]
    cell.scheduleStruct = scheduleItem
    return cell
  }

Over in CustomTableViewCell, I've got this property declared:

    public var scheduleStruct: FullScheduleStruct? {
    didSet {
      configureCell()
    }
    // emptyView to throw on top of a background image
    var gradientView: UIView?

I'm also using Kingfisher to pull images off of the internet, which is what's going on with the ImageResource(downloadURL: url) part. The configureCell() method called when scheduleStruct is set like this:

    private func configureCell() {

    // get the background image
    if let url = scheduleStruct?.show.image?.original {
      let imageUrl = ImageResource(downloadURL: url)
      backgroundImageView.contentMode = .scaleAspectFill
      backgroundImageView.kf.setImage(with: imageUrl)

      // configure the gradientView
      gradientView = UIView(frame: backgroundImageView.frame)
      let gradient = CAGradientLayer()
      gradient.frame = gradientView!.frame
      gradient.colors = [UIColor.clear.cgColor, UIColor.white.cgColor]
      // gradient.locations = [0.0, 1.0]
      gradient.startPoint = CGPoint(x: 0, y: 0)
      gradient.endPoint = CGPoint(x: 0, y: 1)
      gradientView!.layer.insertSublayer(gradient, at: 0)
      backgroundImageView.insertSubview(gradientView!, at: 0)
    }

Any suggestions re: where my mistake lies are greatly appreciated. Thank you for reading.

Upvotes: 1

Views: 325

Answers (1)

Adrian
Adrian

Reputation: 16725

At David Shaw's suggestion, I commented out this line in configureCell()

  // backgroundImageView.kf.setImage(with: imageUrl)

and the gradient drew properly. I deduced I had a timing issue because I'm getting the image asynchronously.

I looked through the method signatures and saw there's one with a completion handler, so I used it instead and it worked:

  backgroundImageView.kf.setImage(with: imageUrl, completionHandler: { (image, error, cacheType, imageUrl) in
    // do stuff
  })

...so I did this.

Upvotes: 1

Related Questions