Ehtesham Hasan Ehtesham Hasan - 3 months ago 18
iOS Question

Misplaced CAGradientLayer on iPhone 6s

I have a few

UILabels
with colored background and I added
CAGradientLayers
to them like below.

CAGradientLayer * gradientLayer = [CAGradientLayer layer];
gradientLayer.colors = [NSArray arrayWithObjects:
(id) [UIColor colorWithWhite:1 alpha:0.3].CGColor,
(id) [UIColor colorWithWhite:0.5 alpha:0.3].CGColor, nil];
gradientLayer.frame = label.bounds;
gradientLayer.cornerRadius = label.layer.cornerRadius;
[label.layer insertSublayer:gradientLayer atIndex:0];


On iPhone 4 and iPhone 5s it looks perfect, but on iPhone 6s the
CAGradientLayers
are misplaced horizontally like the following screenshot.

enter image description here

This problem happens for UIButtons as well.

I am running iOS 9.3.

Answer

What you need is deal with autolayout constraints. This swift code represents what you need to do at viewDidLayoutSubviews method:

class ViewController: UIViewController {

    @IBOutlet weak var button: UIButton!
    let gradientLayer = CAGradientLayer()

    override func viewDidLoad() {
        super.viewDidLoad()


        gradientLayer.colors = [UIColor(white: 1, alpha: 0.3).CGColor,
                                UIColor(white: 0.5, alpha: 0.3).CGColor]
        gradientLayer.frame = button.bounds
        gradientLayer.cornerRadius = button.layer.cornerRadius
        button.layer.insertSublayer(gradientLayer, atIndex: 0)
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        gradientLayer.frame = button.bounds
    }

}
Comments