我有一个滚动视图,里面有一个故事板中的imageview。我有这个代码所在的文件的iboutlet,并引用了这些视图。它们分别称为scrollView
和graph
。我试图以编程方式在scrollview中的图形下面添加很多UILabel,但是我甚至无法显示它。
我添加的宽度约束不会导致任何问题,但其他三个约束会导致运行时错误The view hierarchy is not prepared for the constraint
。我想将标签的顶部限制在图形的底部,标签的左侧限制在scrollview的左侧,标签的底部限制在scrollview的底部。我做错了什么?
更新代码:
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])
答案 0 :(得分:0)
我发现我必须将约束添加到self.view,而不是note1或任何其他元素。
var note1 = UILabel()
note1.text = "test asdf asd fasdf a sdf asdf as dfa sdf safd"
note1.setTranslatesAutoresizingMaskIntoConstraints(false)
scrollView.addSubview(note1)
var widthCons = NSLayoutConstraint(
item: note1,
attribute: .Width,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1, constant: 280)
let topCons = NSLayoutConstraint(
item: note1,
attribute: .Top,
relatedBy: .Equal,
toItem: graph,
attribute: .Bottom,
multiplier: 1, constant: 0);
let bottomCons = NSLayoutConstraint(
item: note1,
attribute: .Bottom,
relatedBy: .Equal,
toItem: scrollView,
attribute: .Bottom,
multiplier: 1, constant: 0);
let leftCons = NSLayoutConstraint(
item: note1,
attribute: .Left,
relatedBy: .Equal,
toItem: scrollView,
attribute: .Left,
multiplier: 1, constant: 0);
self.view.addConstraints([topCons, bottomCons, leftCons, widthCons])