0
所以我一直试图用约束以编程方式将UIVIew添加到UIScrollView。我只是没有在模拟器中看到UIView。 我有一个IBOutlet的UIScrollview ...所以我不知道为什么我遇到这个问题。未能尝试以编程方式在滚动视图中添加UIView约束在SWIFT中
override func viewDidAppear(animated: Bool) {
let ownerUIView:UIView! = UIView()
var innerLabel:UILabel = UILabel()
ownerUIView.translatesAutoresizingMaskIntoConstraints = false
innerLabel.translatesAutoresizingMaskIntoConstraints = false
innerLabel.text = "Test text"
ownerUIView.addSubview(innerLabel)
importantScroll.addSubview(ownerUIView)
ownerUIView.backgroundColor = UIColor.blueColor()
let constraint1 = NSLayoutConstraint(item: ownerUIView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: importantScroll, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 10)
let constraint2 = NSLayoutConstraint(item: ownerUIView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: importantScroll, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 10)
let constraint3 = NSLayoutConstraint(item: ownerUIView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 60)
let constraint4 = NSLayoutConstraint(item: ownerUIView, attribute: .Top , relatedBy: .Equal, toItem: importantScroll, attribute: NSLayoutAttribute.Top , multiplier: 1, constant: 20)
NSLayoutConstraint.activateConstraints([constraint1,constraint2,constraint3,constraint4])
}
我删除了约束,仍然无法看到UILabel或UIVIew。如果我删除UILable,那么我会看到蓝色的UIView。
let ownerUIView:UIView = UIView(frame: CGRect(x: 10, y: 10, width: 200, height: 200))
let innerLabel:UILabel = UILabel(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
ownerUIView.translatesAutoresizingMaskIntoConstraints = false
innerLabel.translatesAutoresizingMaskIntoConstraints = false
innerLabel.text = "Test text"
ownerUIView.addSubview(innerLabel)
importantScroll.addSubview(ownerUIView)
ownerUIView.backgroundColor = UIColor.blueColor()
嗨那里....谢谢你...有没有办法让UIView的右边到10边距? – BostonMacOSX
是否有任何理由以编程方式设置约束?如果您在故事板中应用自动布局,它将会非常简单。你可以参考这个[link](https://spin.atomicobject.com/2014/03/05/uiscrollview-autolayout-ios/)。 – woogii
@BostonMacOSX我更新了我的答案。 – woogii