UIView frame and borders are incorrect

I have a subclass of UIView in which I add CALayersto. I added this UIViewto my presentation through the storyboard. For some reason, access to the frame and borders in init (and in awakeFromNib) is always (0, 0, 1000, 1000). Why is this?

class SliderView: UIView {
    let trackLayer = CAShapeLayer()

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        // The bounds are wrong
        trackLayer.path = UIBezierPath(roundedRect: self.bounds, cornerRadius: 15).cgPath

    }
}
+4
source share
1 answer

I had the same issue in a UITableViewCell. This workaround should work

override func drawRect(rect: CGRect) {
    super.drawRect(rect)
    customInit()
}

var initialized = false
func customInit(){
    if !initialized{
        initialized = true

    // Bounds will be good. Do your stuff here
    }
}

In your case, it should look like this:

class SliderView: UIView {
    let trackLayer = CAShapeLayer()

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        // The bounds are wrong
    }

    override func drawRect(rect: CGRect) {
        super.drawRect(rect)
        customInit()
    }

    var initialized = false
    func customInit() {
        if !initialized {
            initialized = true

            // Bounds will be good.
            trackLayer.path = UIBezierPath(roundedRect: self.bounds, cornerRadius: 15).CGPath
        }
    }
}
-2
source

Source: https://habr.com/ru/post/1654480/


All Articles