UIView框架和边界错误

时间:2016-09-13 15:28:09

标签: ios swift

我有一个UIView子类,我正在添加一些CALayers。我已通过故事板将此UIView添加到我的视图中。出于某种原因,在init(和awakeFromNib)中访问框架和边界总是(0,0,1000,1000)。这是为什么?

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

    }
}

1 个答案:

答案 0 :(得分:-2)

我在UITableViewCell中遇到了同样的问题。 此解决方法应该可以正常工作

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

在你的情况下它应该是这样的:

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