众所周知,UIView
的主/根层,例如view.layer
,将自动调整大小以填充UIView
的框架(但是,根层的子层不会自动调整大小(。
将CALayer
子类化后,如:
class CustomLayer : CALayer {
//...
}
我可以用什么方法来实现";draw";content,以便该层在用作视图的根CAL层时自动调整大小
我问这个问题的原因是因为我当前正在调用方法,例如:
UIBezierPath(roundedRect: self.view.frame, byRoundingCorners: [.topLeft], cornerRadii: CGSize(width: 17, height: 15))
要更新CALayer的路径,但如果能够创建一个自定义的CALayer
,它可以作为UIView
的根层,那将是令人惊讶的,所以我不需要始终如一地更新它的路径。
有人对此有什么建议吗?最终,我正在努力拥有一个层,该层可以为每个角落支持唯一的半径,它将自动填充UIView
并调整大小,而无需持续更新框架。
您可以对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)
}
}