2016-08-05 72 views
1

我試圖以編程方式創建一些文本字段,並使用編程約束將它們放在界面生成器中創建它們,並使用它創建約束將不會像其他所有操作一樣創建編程。所以問題是要創建一個文本字段,我必須使用frame:CGRect(x y width height)。但是,這樣做會覆蓋所有基於其他UI元素的編程約束,以告知放置在哪裏。Swift CGPoint x和y覆蓋了編程約束

// Create username and password entry fields 
let usernameTextField: UITextField 
usernameTextField = UITextField(frame: CGRect(x: 0, y: 0, width: screenWidth - 40 - usernameLabel.bounds.width, height: 30)) // Without this line usernameTextField is uninitialised. 
usernameTextField.textColor = UIColor.black() 
usernameTextField.textAlignment = NSTextAlignment.left 
usernameTextField.placeholder = "username" 
self.view.addSubview(usernameTextField) 
usernameTextField.translatesAutoresizingMaskIntoConstraints = true 

let passwordTextField: UITextField 
passwordTextField = UITextField(frame: CGRect(x: 0, y: 0, width: screenWidth - 40 - passwordLabel.bounds.width, height: 30)) 
passwordTextField.textColor = UIColor.black() 
passwordTextField.textAlignment = NSTextAlignment.left 
passwordTextField.placeholder = "password" 
self.view.addSubview(passwordTextField) 
passwordTextField.translatesAutoresizingMaskIntoConstraints = true 

// Constraints for username and password entry fields 
// Horizontal placement 
usernameTextField.leadingAnchor.constraint(equalTo: usernameLabel.trailingAnchor).isActive = true 
passwordTextField.leadingAnchor.constraint(equalTo: passwordLabel.trailingAnchor).isActive = true 

// Verticle placement 
usernameTextField.bottomAnchor.constraint(equalTo: usernameUnderline.topAnchor).isActive = true 
passwordTextField.bottomAnchor.constraint(equalTo: passwordUnderline.topAnchor).isActive = true 

//Width 
usernameTextField.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true 
passwordTextField.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true 

那麼如何以編程方式創建這些文本字段並使用約束來放置它們?

回答

2

一旦開始向UIView添加約束,您必須全力以赴。在您的字段上設置translatesAutoresizingMaskIntoConstraints = false,然後爲所需的寬度,高度和位置添加約束。

在這種情況下,當你創建你不通過一幀到UITextField構造:

let usernameTextField = UITextField() 

看起來你已經通過設置它的前端和後端錨佔usernameTextField的長度。因此,請爲其高度添加一個約束:

usernameTextField.heightAnchor.constraintEqualToConstant(30) 

然後重複此操作以獲得您的passwordTextField

+0

非常感謝你,它完美的工作。我不知道你可以使用= UITextField()來初始化。 – RufusV

+0

不客氣!我很高興能夠提供幫助。 – vacawama