CAShapeLayer没有出现

时间:2018-12-27 17:47:00

标签: ios uiview swift4 cashapelayer swift4.2

我正在尝试向视图添加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)
...
}

我真的不明白发生了什么。请帮忙!

1 个答案:

答案 0 :(得分:0)

我建议:

  1. init中添加子层(因此,它只能添加一次,并且只能添加一次);
  2. frame中配置其pathlayoutSubviews(因此,如果通过约束或其他某种方式调整了其大小,则该层将相应地更新);
  3. 添加尺寸基于当前视图大小的子视图/子图层时,请引用视图的bounds(当前视图内的坐标系),而不是frame或{{1 }}(两者都在超级视图的坐标系中);和
  4. 使用center方法或addSublayer方法,但不能同时使用两者。

因此,添加layerClass作为子层:

CAShapeLayer

屈服:

enter image description here


或者,如果您想使用@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