我正在尝试向视图添加CAShapeLayer
。但是,当我将customView
添加到ViewCOntroller的视图时,shapeLayer不会显示。捕获层次结构表明该层甚至都没有插入到视图中。这是代码:
override class var layerClass: AnyClass {
return CAShapeLayer.self
}
...
override func didMoveToSuperview() {
let diameter = min(self.frame.width, self.frame.height)
let path = UIBezierPath(arcCenter: self.center, radius: diameter/2, startAngle: 0, endAngle: CGFloat.pi*2, clockwise: true)
let sLayer = CAShapeLayer()
sLayer.frame = bounds
sLayer.path = path.cgPath
sLayer.fillMode = .backwards
sLayer.fillColor = UIColor.blue.cgColor//bubbleColor?.cgColor
layer.addSublayer(sLayer)
}
在ViewController中:
override func viewDidLoad() {
super.viewDidLoad()
let node = Node(frame: CGRect(origin: self.view.center, size: CGSize(width: 250, height: 250)))
self.view.addSubview(node)
...
}
我真的不明白发生了什么。请帮忙!
答案 0 :(得分:0)
我建议:
init
中添加子层(因此,它只能添加一次,并且只能添加一次); frame
中配置其path
和layoutSubviews
(因此,如果通过约束或其他某种方式调整了其大小,则该层将相应地更新); bounds
(当前视图内的坐标系),而不是frame
或{{1 }}(两者都在超级视图的坐标系中);和center
方法或addSublayer
方法,但不能同时使用两者。因此,添加layerClass
作为子层:
CAShapeLayer
屈服:
或者,如果您想使用@IBDesignable
class CircleView: UIView {
@IBInspectable var bubbleColor: UIColor = .blue { didSet { shapeLayer.fillColor = bubbleColor.cgColor } }
private lazy var shapeLayer: CAShapeLayer = {
let sLayer = CAShapeLayer()
sLayer.fillColor = bubbleColor.cgColor
return sLayer
}()
override init(frame: CGRect = .zero) {
super.init(frame: frame)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
override func layoutSubviews() {
super.layoutSubviews()
shapeLayer.frame = bounds
updatePath()
}
}
// MARK: - Utility methods
private extension CircleView {
func configure() {
layer.addSublayer(shapeLayer)
}
func updatePath() {
let diameter = min(bounds.width, bounds.height)
let arcCenter = CGPoint(x: bounds.midX, y: bounds.midY)
shapeLayer.path = UIBezierPath(arcCenter: arcCenter, radius: diameter / 2, startAngle: 0, endAngle: .pi * 2, clockwise: true).cgPath
}
}
方法:
layerClass