D-A UK
D-A UK

Reputation: 1174

TableView background gradient glitching

I have a gradient layer set for a table view, using the following code:

func setGradientToTableView(_ topColor:UIColor, _ bottomColor:UIColor) {

    let gradientBackgroundColors = [topColor.cgColor, bottomColor.cgColor]
    let gradientLocations = [0.0,1.0]

    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = gradientBackgroundColors
    gradientLayer.locations = gradientLocations as [NSNumber]

    gradientLayer.frame = tableView.bounds
    let backgroundView = UIView(frame: tableView.bounds)
    backgroundView.layer.insertSublayer(gradientLayer, at: 0)
    tableView.backgroundView = backgroundView

}

And this:

setGradientToTableView(UIColor(red: 125/255.0, green: 125/255.0, blue: 125/255.0, alpha: 1.0), UIColor(red: 125/255.0, green: 125/255.0, blue: 0/255.0, alpha: 1.0)).

The problem is coming when I run the app. The gradient layer will be the size of the table view for the device and orientation that is selected in the storyboard.

Does anyone know how to fix this? - btw my constraints for the table view are navigation bar bottom, leading, trailing, and safe area bottom

Edit: Here is a screenshot

enter image description here

Upvotes: 1

Views: 174

Answers (1)

apptimal
apptimal

Reputation: 494

Probably the problem is that you set the gradient in the viewDidLoad() method, where the table view has not been drawn yet and its frame is the default frame from XIB/storyboard. You should call this in didLayoutSubviews() like this:

var gradientLayer: CAGradientLayer?
func didLayoutSubviews() {
    if (gradientLayer == nil) {
        setGradientToTableView(UIColor(red: 125/255.0, green: 125/255.0, blue: 125/255.0, alpha: 1.0), UIColor(red: 125/255.0, green: 125/255.0, blue: 0/255.0, alpha: 1.0))
    }
}

Keep the reference to the gradient layer in your class to make sure you only set the gradient once, because didLayoutSubviews is called multiple times.

Upvotes: 4

Related Questions