自动布局时,界限始终为零

时间:2014-12-02 11:43:36

标签: ios swift autolayout key-value-observing

我正在尝试在其边界发生变化时更新我的​​观点。我的视图在其超级视图中使用自动布局进行了布局。

这是我观察边界的代码:

public override init() {
        super.init()
        self.addObserver(self, forKeyPath: "bounds", options: .New, context: nil)
    }

    public override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
        NSLog("[SkewedSplitView]: observer: %fx%f, %f:%f", self.bounds.width, self.bounds.height, self.bounds.origin.x, self.bounds.origin.y)
    }

输出:

  

2014-12-02 12:35:35.018 XXX [7365:2001261] [SkewedSplitView]:观察者:   0.000000x0.000000,0.000000:0.000000

我甚至试过Swits观察员:

override public var bounds: CGRect {
        didSet {
            NSLog("[SkewedSplitView]: bounds: %fx%f, %f:%f", self.frame.width, self.frame.height, self.frame.origin.x, self.frame.origin.y)
        }
    }

输出:

  

2014-12-02 12:35:35.012 XXX [7365:2001261] [SkewedSplitView]:界限:   0.000000x0.000000,0.000000:0.000000

两者都被称为一次。 继承了我的代码(使用制图):

        let betters = SkewedSplitView()
        betters.backgroundColor = UIColor.greenColor()
        self.addSubview(betters)

        constrain(betters, friends) { (betters, friends) in
            betters.bottom == friends.top - 3
            betters.leading == betters^.leading
            betters.trailing == betters^.trailing
            betters.height == 40
        }

在屏幕上,视图布局得很好,框架正确。

1 个答案:

答案 0 :(得分:0)

使用autolayout时,调用init时不会建立边界。您可以使用ViewDidLayoutSubviews或ViewDidAppear。将NSLog置于其中任何一个中,您将获得与零不同的界限。 此致