【问题标题】:Swift: How to subclass CALayer so it resizes automatically?Swift:如何继承 CALayer 以便它自动调整大小?
【发布时间】:2021-04-08 01:45:40
【问题描述】:

已知UIView 的主层/根层,例如view.layer,会自动调整大小以填充UIView 的框架(但是,根层的子层不会自动调整大小)。

在子类化CALayer之后像:

class CustomLayer : CALayer {
    //...
}

我可以实现哪些方法来“绘制”内容以便在用作视图的根 CALayer 时图层会自动调整大小?


我问这个的原因是因为我当前正在调用方法,例如:

UIBezierPath(roundedRect: self.view.frame, byRoundingCorners: [.topLeft], cornerRadii: CGSize(width: 17, height: 15))

要更新 CALayer 的路径,但是能够创建一个自定义的 CALayer 可以作为 UIView 的根层会很棒,所以我不需要持续更新它的路径。

有人对此有什么建议吗?最终,我正在努力创建一个可以支持每个角的唯一半径的图层,该图层将自动填充UIView 并调整大小,而无需不断更新框架。

【问题讨论】:

  • 既然 UIView 是知道大小变化的,它应该负责子层的大小调整。一个好的实现是在 UIView 的 layoutSubviews 函数中重绘你的子层。

标签: ios swift uiview autolayout calayer


【解决方案1】:

你可以继承 UIView,覆盖 layerClass 并返回一个 CAShapeLayer:

class Shape: UIView {

    override public class var layerClass: AnyClass { CAShapeLayer.self }
    var shapeLayer: CAShapeLayer { layer as! CAShapeLayer }
    
    private var bezierPath: UIBezierPath = UIBezierPath() { didSet { shapeLayer.path = bezierPath.cgPath } }
    
    var fillColor: UIColor = .green { didSet { shapeLayer.fillColor = fillColor.cgColor } }
    var strokeColor: UIColor = .blue { didSet { shapeLayer.strokeColor = strokeColor.cgColor } }
    var lineWidth: CGFloat = 2 { didSet { shapeLayer.lineWidth = lineWidth } }
    
    override func didMoveToSuperview() {
        updateShape()
        shapeLayer.fillColor = fillColor.cgColor
        shapeLayer.strokeColor = strokeColor.cgColor
        shapeLayer.lineWidth = lineWidth
    }
    func updateShape() {
        bezierPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.topLeft], cornerRadii: CGSize(width: 17, height: 15))
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        print(#function)
        updateShape()
    }
    override public func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        print(#function)
        // you can change the color of your shape here if needed (dark/light mode)
    }
}

【讨论】:

    猜你喜欢
    • 2011-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多