Misplaced CAGradientLayer on iPhone 6s

怎甘沉沦 提交于 2020-01-03 02:32:05

问题


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.

This problem happens for UIButtons as well.

I am running iOS 9.3.


回答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
    }

}


来源:https://stackoverflow.com/questions/39255885/misplaced-cagradientlayer-on-iphone-6s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!