约束和子层(CALayer)不更新

时间:2017-08-18 07:28:04

标签: ios

我在superView中创建了一个左边框

...
    var leftLayer: CALayer?
    override public func awakeFromNib() {
        super.awakeFromNib()
        self.leftLayer = CALayer()
        self.leftLayer?.borderColor = UIColor.red.cgColor
        self.leftLayer?.borderWidth = 1
        self.layer.addSublayer(self.leftLayer!)
...

然后在layoutSubviews中我尝试根据约束更新边框:

...
override public func layoutSubviews() {
        super.layoutSublayers(of: layer)
        leftLayer!.frame = CGRect(x: 0,
                                  y: 0,
                                  width: 1,
                                  height: self.frame.size.height)

}
...

但是,子CALayers没有遵循顶级的CALayer / UIViews约束。我看过this,但无法将图层添加到超级视图中。

你知道如何让子CALayer遵循包含UIView的约束吗?

1 个答案:

答案 0 :(得分:2)

覆盖视图的frame属性以调整其子图层框架:

override var frame: CGRect {
    didSet{
        leftLayer!.frame = CGRect(x: 0,
                                  y: 0,
                                  width: 1,
                                  height: self.frame.size.height)
    }
}