0
我發現未實現約束時通過編程方式向故事板上的現有視圖鍵入約束。這裏是我有什麼:以編程方式向故事板上的現有視圖添加NSConstraints
class ViewController: UIViewController {
@IBOutlet weak var textField2: UITextField! {
didSet {
textField2.delegate = self
}
}
func viewDidLoad() {
super.viewDidLoad()
let superview = self.view
let textField1 = UITextField()
textField1.backgroundColor = UIColor.greenColor()
textField1.placeholder = "test text field"
view.addSubview(textField1)
textField1.translatesAutoresizingMaskIntoConstraints = false
superview.addConstraint(NSLayoutConstraint(item: textField1, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1, constant: superview.frame.width * 0.50))
superview.addConstraint(NSLayoutConstraint(item: textField1, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: superview.frame.height * 0.05))
superview.addConstraint(NSLayoutConstraint(item: textField1, attribute: .CenterX, relatedBy: .Equal, toItem: superview, attribute: .CenterX, multiplier: 1, constant: 0))
superview.addConstraint(NSLayoutConstraint(item: textField1, attribute: .CenterY, relatedBy: .Equal, toItem: superview, attribute: .CenterY, multiplier: 1, constant: 0))
textField2.translatesAutoresizingMaskIntoConstraints = false
superview.addConstraint(NSLayoutConstraint(item: textField2, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1, constant: superview.frame.width * 0.50))
superview.addConstraint(NSLayoutConstraint(item: textField2, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: superview.frame.height * 0.05))
superview.addConstraint(NSLayoutConstraint(item: textField2, attribute: .CenterX, relatedBy: .Equal, toItem: superview, attribute: .CenterX, multiplier: 1, constant: 0))
superview.addConstraint(NSLayoutConstraint(item: textField2, attribute: .CenterY, relatedBy: .Equal, toItem: superview, attribute: .CenterY, multiplier: 1, constant: 0))
}
}
textField1
完美的作品。它被添加到視圖的中心。然而,textField2
,我拖放到故事板上,偏離了中心。爲什麼發生這種情況?
感謝
另見我回答這個問題,這實際上是完全一樣的問題,設置了限制:http://stackoverflow.com/questions/35421925/scrunched-layout – matt
感謝您的回答 – Alex