繁体   English   中英

使用AutoLayout(swift)以编程方式将UILabel添加到ScrollView

[英]Adding UILabel to ScrollView Programmatically with AutoLayout (swift)

我有一个滚动视图,并且在其中有一个故事板中的图像视图。 我将此代码所在的文件包含iboutlet,并引用了这些视图。 它们分别称为scrollViewgraph 我试图以编程方式在滚动视图内的图形下方添加许多UILabel,但我什至无法显示。

我添加的width约束不会引起任何问题,但是其他三个约束会出现运行时错误,说明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])

我发现必须将约束添加到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])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM