简体   繁体   English

UIView框架和边界错误

[英]UIView frame and bounds wrong

I have a UIView subclass that I'm adding some CALayers to. 我有一个要添加一些CALayers的UIView子类。 I've added this UIView to my view via storyboard. 我已通过情节UIView将此UIView添加到视图中。 For some reason accessing the frame and bounds in the init (and in awakeFromNib) are always (0, 0, 1000, 1000). 出于某种原因,在init中(以及在awakeFromNib中)访问框架和边界始终为(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. 我在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
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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