Home > Enterprise >  Gradient background view for table view
Gradient background view for table view

Time:10-01

I want to use a gradient background for my table view and I do it successfully with this method:

private func setBackgroundViewColor() {
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [#colorLiteral(red: 0.0923477529, green: 0.1613951182, blue: 0.3891475176, alpha: 1).cgColor, #colorLiteral(red: 0.1546722437, green: 0.02495219428, blue: 0.2035871579, alpha: 1).cgColor]
        gradientLayer.locations = [NSNumber(value: 0.0), NSNumber(value: 1.0)]
        
        gradientLayer.frame = tableView.bounds
        let backgroundView = UIView(frame: tableView.bounds)
        backgroundView.layer.addSublayer(gradientLayer)
        tableView.backgroundView = backgroundView
    } 

But this only works with standard cells with storyboard, if I try to register custom cell

tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellID)

then the gradient does not appear and I get the following

enter image description here

How can it be solved?

CodePudding user response:

Is the gradient the blue color behind the cells? It looks like the custom cell has a different background color. May not be the best solution, but you can try this in ViewDidLoad. So then your tableView gradient color should show through the cells.

UITableViewCell.self.appearance().backgroundColor = UIColor.clear

CodePudding user response:

It turned out that you need to call the func setBackgroundViewColor() in viewWillAppear and then everything works fine.

  • Related