【发布时间】:2015-02-04 17:58:36
【问题描述】:
我有一个滚动视图,里面有一个故事板中的图像视图。我有这个代码所在的文件的 iboutlets 以及对这些视图的引用。它们分别称为scrollView 和graph。我正在尝试以编程方式在滚动视图内的图形下方添加很多 UILabel,但我什至无法显示。
我添加的宽度约束不会导致任何问题,但其他三个约束会出现运行时错误,即 The view hierarchy is not prepared for the constraint。我想将标签的顶部限制在图表的底部,将标签的左侧限制在滚动视图的左侧,将标签的底部限制在滚动视图的底部。我做错了什么?
更新代码:
var noteBodyLabel = UILabel()
noteBodyLabel.text = "test asdf asd fasdf a sdf asdf as dfa sdf safd"
noteBodyLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
var widthCons = NSLayoutConstraint(
item: noteBodyLabel,
attribute: .Width,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1, constant: 280)
let topCons = NSLayoutConstraint(
item: noteBodyLabel,
attribute: .Top,
relatedBy: .Equal,
toItem: graph,
attribute: .Bottom,
multiplier: 1, constant: 0);
let bottomCons = NSLayoutConstraint(
item: noteBodyLabel,
attribute: .Bottom,
relatedBy: .Equal,
toItem: scrollView,
attribute: .Bottom,
multiplier: 1, constant: 0);
let leftCons = NSLayoutConstraint(
item: noteBodyLabel,
attribute: .Left,
relatedBy: .Equal,
toItem: scrollView,
attribute: .Left,
multiplier: 1, constant: 0);
scrollView.addSubview(noteBodyLabel)
noteBodyLabel.addConstraints([topCons,leftCons,bottomCons,widthCons])
【问题讨论】:
-
错误是因为您在两个不在同一棵树中的视图之间创建约束。在添加约束之前调用
scrollView.addSubview(noteBodyLabel)。 -
@AaronBrager 看看我更新的代码 - 它仍在发生
-
'not prepare for the constraint'意味着您的约束中的一个视图尚未添加到视图层次结构中。您确定所有视图都已添加为子视图吗?
-
@ChrisTruman 我的意思是我知道图形是 scrollView 的有效子视图,我知道 scrollView 是 self.view 的有效子视图。 graph 和 scrollView 都是通过故事板添加的,我的代码在 viewDidLoad 中运行。会不会跟这有关系?
-
可能是viewDidLoad不是加约束的合适时机:stackoverflow.com/a/19398589/150920
标签: ios objective-c iphone swift uiscrollview