已知的主/根层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子类化,覆盖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)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句