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