2016-04-21 3 views
0

Вот мой простой код, чтобы добавить ограничение:Добавить ограничение программно Просмотры

import UIKit 

class ViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     let contentView = UIView() 
     contentView.backgroundColor = UIColor.greenColor() 
     contentView.frame.size.width = 250 
     contentView.frame.size.height = 100 
     contentView.center = view.center 
     view.addSubview(contentView) 

     let userNameLabel = UILabel() 
     userNameLabel.translatesAutoresizingMaskIntoConstraints = false 
     userNameLabel.text = "Username:" 
     contentView.addSubview(userNameLabel) 

     let passwordLabel = UILabel() 
     passwordLabel.translatesAutoresizingMaskIntoConstraints = false 
     passwordLabel.text = "Password:" 
     contentView.addSubview(passwordLabel) 

     let usernameTextField = UITextField() 
     usernameTextField.translatesAutoresizingMaskIntoConstraints = false 
     usernameTextField.borderStyle = .RoundedRect 
     contentView.addSubview(usernameTextField) 

     let passwordTextField = UITextField() 
     passwordTextField.translatesAutoresizingMaskIntoConstraints = false 
     passwordTextField.borderStyle = .RoundedRect 
     contentView.addSubview(passwordTextField) 

     let submitButton = UIButton() 
     submitButton.translatesAutoresizingMaskIntoConstraints = false 
     submitButton.setTitle("Submit", forState: .Normal) 
     submitButton.setTitleColor(UIColor.redColor(), forState: .Normal) 
     submitButton.setTitleColor(UIColor.redColor(), forState: .Highlighted) 
     contentView.addSubview(submitButton) 

     // For Username 
     NSLayoutConstraint(item: userNameLabel, attribute: .Leading, relatedBy: .Equal, toItem: contentView, attribute: .LeadingMargin, multiplier: 1, constant: 0).active = true 
     NSLayoutConstraint(item: userNameLabel, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1, constant: 10).active = true 
     NSLayoutConstraint(item: usernameTextField, attribute: .Trailing, relatedBy: .Equal, toItem: contentView, attribute: .TrailingMargin, multiplier: 1.0, constant: 0.0).active = true 
     NSLayoutConstraint(item: usernameTextField, attribute: .Leading, relatedBy: .Equal, toItem: userNameLabel, attribute: .Trailing, multiplier: 1.0, constant: 3).active = true 
     NSLayoutConstraint(item: userNameLabel, attribute: .Baseline, relatedBy: .Equal, toItem: usernameTextField, attribute: .Baseline, multiplier: 1.0, constant: 0.0).active = true 
     // For Password 
     NSLayoutConstraint(item: passwordLabel, attribute: .Leading, relatedBy: .Equal, toItem: contentView, attribute: .LeadingMargin, multiplier: 1, constant: 0).active = true 
     NSLayoutConstraint(item: passwordLabel, attribute: .Top, relatedBy: .Equal, toItem: userNameLabel, attribute: .Bottom, multiplier: 1, constant: 15).active = true 
     NSLayoutConstraint(item: passwordTextField, attribute: .Trailing, relatedBy: .Equal, toItem: contentView, attribute: .TrailingMargin, multiplier: 1.0, constant: 0.0).active = true 
     NSLayoutConstraint(item: passwordTextField, attribute: .Leading, relatedBy: .Equal, toItem: passwordLabel, attribute: .Trailing, multiplier: 1.0, constant: 3).active = true 
     NSLayoutConstraint(item: passwordLabel, attribute: .Baseline, relatedBy: .Equal, toItem: passwordTextField, attribute: .Baseline, multiplier: 1.0, constant: 0.0).active = true 
     // For Button 
     NSLayoutConstraint(item: submitButton, attribute: .Top, relatedBy: .Equal, toItem: passwordLabel, attribute: .Bottom, multiplier: 1.0, constant: 8.0).active = true 
     NSLayoutConstraint(item: submitButton, attribute: .CenterX, relatedBy: .Equal, toItem: contentView, attribute: .CenterX, multiplier: 1.0, constant: 0.0).active = true 
    } 

} 

Но почему это выглядит так, я хочу, возглавляющие passWordTextField «s является 3 к задней части passWordLabel:

enter image description here

Я смотрю на эту линию и не может найти какие-либо проблемы:

NSLayoutConstraint(item: passwordTextField, attribute: .Leading, relatedBy: .Equal, toItem: passwordLabel, attribute: .Trailing, multiplier: 1.0, constant: 3).active = true 

Любая помощь будет оценена по достоинству. Спасибо

ответ

2

Проблема в том, что ярлык и текстовое поле имеют одинаковую приоритетность. Вам необходимо определить, какой из них следует определить по приоритетам. Пример:

userNameLabel.setContentHuggingPriority(251, forAxis: .Horizontal) 
passwordLabel.setContentHuggingPriority(251, forAxis: .Horizontal) 
+0

Это сработало. Потому что я думаю, что UILabel автоматически установит ширину базы в тексте внутри нее. Но почему userNameLabel работает, пока парольLabel не работает. – Khuong

+0

Но когда я меняю текст на passwordLabel, это выглядит так плохо. – Khuong

+0

Каким образом? Просто попробовал, и здесь все отлично. –

0

Проблема заключается в том, что: эта линия:

NSLayoutConstraint(item: passwordTextField, attribute: .Leading, relatedBy: .Equal, toItem: passwordLabel, attribute: .Trailing, multiplier: 1.0, constant: 3).active = true 

должны предстать перед этой строкой:

NSLayoutConstraint(item: passwordTextField, attribute: .Trailing, relatedBy: .Equal, toItem: contentView, attribute: .TrailingMargin, multiplier: 1.0, constant: 0.0).active = true 

код для пароля будет выглядеть следующим образом:

// For Password 
NSLayoutConstraint(item: passwordLabel, attribute: .Leading, relatedBy: .Equal, toItem: contentView, attribute: .LeadingMargin, multiplier: 1, constant: 0).active = true 
NSLayoutConstraint(item: passwordLabel, attribute: .Top, relatedBy: .Equal, toItem: userNameLabel, attribute: .Bottom, multiplier: 1, constant: 15).active = true 
NSLayoutConstraint(item: passwordTextField, attribute: .Leading, relatedBy: .Equal, toItem: passwordLabel, attribute: .Trailing, multiplier: 1.0, constant: 3).active = true 
NSLayoutConstraint(item: passwordTextField, attribute: .Trailing, relatedBy: .Equal, toItem: contentView, attribute: .TrailingMargin, multiplier: 1.0, constant: 0.0).active = true 
NSLayoutConstraint(item: passwordLabel, attribute: .Baseline, relatedBy: .Equal, toItem: passwordTextField, attribute: .Baseline, multiplier: 1.0, constant: 0.0).active = true 

enter image description here

Смежные вопросы