Misplaced CAGradientLayer on iPhone 6s

时间:2016-08-31 17:42:25

标签: ios objective-c iphone cagradientlayer

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.

1 个答案:

答案 0 :(得分:1)

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
    }

}