2016-03-05 103 views
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,我拖放到故事板上,偏離了中心。爲什麼發生這種情況?

感謝

回答

1

的問題是,如果一個觀點來自故事板,就像你textField2,它已經有約束。說textField2.translatesAutoresizingMaskIntoConstraints = false不會神奇地解決這個問題。您還需要以某種方式掌握這些約束,並在將自己的約束應用於代碼之前將其刪除。這可能會很棘手,而不是這樣做,這就是爲什麼你的觀點是行爲不端。最好是,在這個階段,你要遵循這些簡單的規則:

  • 如果視圖來自於故事板,只是在故事板

  • 設置它的約束,但是如果一個視圖中所作代碼,現在你可以說translatesAutoresizingMaskIntoConstraints = false和代碼

+1

另見我回答這個問題,這實際上是完全一樣的問題,設置了限制:http://stackoverflow.com/questions/35421925/scrunched-layout – matt

+0

感謝您的回答 – Alex

相關問題