为什么渐变不能覆盖视图的整个宽度 [英] Why gradient doesn't cover the whole width of the view

查看:87
本文介绍了为什么渐变不能覆盖视图的整个宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对主屏幕的顶部,左侧和右侧受约束的视图应用渐变,但是由于某种原因,渐变不能覆盖所应用视图的整个宽度(请参见图片中的黄色).

I'm trying to apply a gradient to a view which is constraint to the top, left and right of the main screen but for some reason the gradient doesn't cover the whole width of the view that is applied to (see the yellow in the picture).

class ViewController: UIViewController {

    @IBOutlet weak var myView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let gradient = CAGradientLayer()
        gradient.colors = [UIColor.blue.cgColor, UIColor.white.cgColor]
        gradient.startPoint = CGPoint(x:00, y:00)
        gradient.endPoint = CGPoint(x:0, y:0.6)
        gradient.frame = myView.bounds
        myView.clipsToBounds = true
        myView.layer.insertSublayer(gradient, at: 0)
    }
}

我在做什么错了?

推荐答案

问题可能是您在viewDidLoad()中添加了渐变图层.直到viewDidLoad()之后,视图才被设置为其最终大小.

The problem is likely that you are adding the gradient layer in viewDidLoad(). A view doesn't get set to it's final size until after viewDidLoad().

您的View Controller可能在XIB/Storyboard中设置为与运行时不同的屏幕尺寸. (假设您将其设置为iPhone SE大小,但在6上运行它.6的屏幕稍宽一些,因此,当第一次加载视图时,该图层将设置为iPhone SE的宽度.然后将调整视图的大小,但永远不会调整图层的大小.)

Your view controller may be set up in your XIB/Storyboard for a different screen-size than you're running it on. (Say you have it set to iPhone SE size, but you're running it on a 6. The 6's screen is a little wider, so the layer will get set to the width of the iPhone SE, when the view is first loaded. Then the view will be resized, but the layer's size will never be adjusted.)

您应该实现UIViewController方法viewDidLayoutSubviews(),并在该方法中调整图层的框架:

You should implement the UIViewController method viewDidLayoutSubviews(), and in that method, adjust the layer's frame:

override func viewDidLayoutSubviews() {
  gradientLayer.frame = self.view.bounds
}

这样,如果调整了视图的大小(例如,由于自动旋转),则将相应地自动调整渐变层.

That way if the view gets resized (due to auto-rotation, for example) the gradient layer will be automatically adjusted accordingly.

如Sulthan所指出的,默认情况下,对图层框架的更改会设置为动画.您可能应该将帧更改包装在CATransaction.begin/CATransaction.end中并禁用操作,如下所示:

As pointed out by Sulthan, changes to a layer's frame are animated by default. You should probably wrap the frame change in a CATransaction.begin/CATransaction.end and disable actions, like below:

override func viewDidLayoutSubviews() {
  CATransaction.begin()
  CATransaction.setDisableActions(true)
  gradientLayer.frame = self.view.bounds
  CATransaction.commit()
}

这篇关于为什么渐变不能覆盖视图的整个宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆