Tometoyou Tometoyou - 1 month ago 31
Swift Question

UIView frame and bounds wrong

I have a UIView subclass that I'm adding some

CALayers
to. I've added this
UIView
to my view via storyboard. For some reason accessing the frame and bounds in the init (and in awakeFromNib) are 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

}
}

Answer

I had the same problem in 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
        }
    }
}
Comments