Swift CGPoint x 和 y 覆盖编程约束

Swift CGPoint x and y overrides programatic constraints

我正在尝试以编程方式创建一些文本字段,并使用编程约束将它们布局为在界面生成器中创建它们并使用它来创建约束将不起作用,因为其他所有内容都是以编程方式创建的。所以问题是要创建一个文本字段,我必须使用 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

那么如何以编程方式创建这些文本字段并使用约束来放置它们?

一旦开始向 UIView 添加约束,就必须全力以赴。在字段上设置 translatesAutoresizingMaskIntoConstraints = false,然后为所需的宽度、高度和位置添加约束。

在这种情况下,您在创建框架时不会将框架传递给 UITextField 构造函数:

let usernameTextField = UITextField()

您似乎已经通过设置前导和尾随锚点来计算 usernameTextField 的长度。所以为其高度添加一个约束:

usernameTextField.heightAnchor.constraintEqualToConstant(30)

并为您的 passwordTextField 重复此操作。