Ios Swift CGX和y点覆盖程序约束

Ios Swift CGX和y点覆盖程序约束,ios,swift,autolayout,nslayoutconstraint,Ios,Swift,Autolayout,Nslayoutconstraint,我试图以编程方式创建一些文本字段,并使用编程约束在界面生成器中创建文本字段时对其进行布局,而使用它来创建约束将不起作用,因为其他所有内容都是以编程方式创建的。所以问题是要创建一个文本字段,我必须使用frame:CGRect(x-y-width-height)。但这样做会覆盖所有程序约束,这些约束根据其他UI元素指示放置在何处 // Create username and password entry fields let usernameTextField: UITextField userna

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

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

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

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

let usernameTextField = UITextField()
看起来您已经在通过设置其前导和尾随锚来计算
usernameTextField
的长度。因此,为其高度添加一个约束:

usernameTextField.heightAnchor.constraintEqualToConstant(30)

对您的
密码文本字段重复此操作

非常感谢,它工作得非常好。我不知道您可以使用=UITextField()进行初始化。