Ehtesham Hasan Ehtesham Hasan - 1 year ago 101
iOS Question

Misplaced CAGradientLayer on iPhone 6s

I have a few

with colored background and I added
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
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 Source

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() {

        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() {

        gradientLayer.frame = button.bounds

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download