我有两个观点。 subLabel
和tinyImage
我希望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 :(得分:1)
您似乎在视图位置添加约束。您可以尝试将约束添加到tinyImage的超级视图中。
如果你支持iOS8 +,你可以写:
horizontalConstraint.active = true
而不是
tinyImage.addConstraint(horizontalConstraint)
这会自动调用addConstraint / removeConstraint。