Is there a way for Interface Builder to render IBDesignable views which don't override drawRect:

前端 未结 8 605
不知归路
不知归路 2020-12-02 03:45

I very rarely override drawRect in my UIView subclasses, usually preferring to set layer.contents with pre-rendering images and often employing multiple sublaye

8条回答
  •  佛祖请我去吃肉
    2020-12-02 04:25

    I think layoutSubviews is the simplest mechanism.

    Here is a (much) simpler example in Swift:

    @IBDesignable
    class LiveLayers : UIView {
    
        var circle:UIBezierPath {
            return UIBezierPath(ovalInRect: self.bounds)
        }
    
        var newLayer:CAShapeLayer {
            let shape = CAShapeLayer()
            self.layer.addSublayer(shape)
            return shape
        }
        lazy var myLayer:CAShapeLayer = self.newLayer
    
        // IBInspectable proeprties here...
        @IBInspectable var pathLength:CGFloat = 0.0 { didSet {
            self.setNeedsLayout()
        }}
    
        override func layoutSubviews() {
            myLayer.frame = self.bounds // etc
            myLayer.path = self.circle.CGPath
            myLayer.strokeEnd = self.pathLength
        }
    }
    

    I haven't tested this snippet, but have used patterns like this before. Note the use of the lazy property delegating to a computed property to simplify initial configuration.

提交回复
热议问题