我正在尝试以编程方式创建一些文本字段,并使用编程约束将它们布局为在界面构建器中创建它们并使用它来创建约束将无法正常工作,因为其他所有内容都是以编程方式创建的。所以问题是要创建一个Text字段,我必须使用frame:CGRect(x y width height)。但是这样做会覆盖所有编程约束,告诉基于其他UI元素放置在哪里。
// 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
那么我怎么能以编程方式创建这些文本字段并使用约束来放置它们呢?
答案 0 :(得分:2)
一旦开始向UIView
添加约束,您就必须全力以赴。在字段上设置translatesAutoresizingMaskIntoConstraints = false
,然后为所需的宽度,高度和位置添加约束。
在这种情况下,您在创建框架时不会将框架传递给UITextField
构造函数:
let usernameTextField = UITextField()
通过设置其前导和尾随锚点,您似乎已经考虑了usernameTextField
的长度。因此,为其高度添加一个约束:
usernameTextField.heightAnchor.constraintEqualToConstant(30)
并为您的passwordTextField
重复此操作。