简体   繁体   中英

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

    }
}

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
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM