2016-04-12 80 views
1

我有兩個視圖。 subLabeltinyImage水平限制導致iOS崩潰

我想tinyImage是subLabel的權利,10像素間距。這是我有:

 let horizontalConstraint = NSLayoutConstraint(item: subLabel, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: tinyImage, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 10) 
     tinyImage.addConstraint(horizontalConstraint) 

當我運行這段代碼,它崩潰了,我看是這樣的:

The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x7fe89a6ece10 UILabel:0x7fe89a764cf0'2'.trailing == UIImageView:0x7fe89a765bb0.leading + 10> 
    When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView(UIConstraintBasedLayout) _viewHierarchyUnpreparedForConstraint:] to debug. 
+0

是tinyImage和subLabel同胞視圖嗎? –

+0

你應該確保'tinyImage'和'subLabel'都被添加到視圖層次結構中,並且你應該將約束添加到公共超級視圖而不是'tinyImage',所以可能是'self.addConstraint'或'self.view。 addConstraint'取決於'self'是什麼 – Paulw11

+0

@ReyGonzales是的,infoView將兩個視圖添加爲子視圖。 – TIMEX

回答

1

好像要添加視圖位置約束。您可以嘗試將約束添加到tinyImage的超級視圖。

如果要支持iOS8上+你可以寫:的

horizontalConstraint.active = true 

代替

tinyImage.addConstraint(horizontalConstraint) 

這會自動調用addConstraint/removeConstraint。

+0

你的意思是'''.active = true'''而不是'''activate'''? – TIMEX

+0

是的,對不起。我將編輯迴應。 – Dario