【问题标题】:Swift CGPoint x and y overrides programatic constraintsSwift CGPoint x 和 y 覆盖编程约束
【发布时间】:2016-08-05 08:00:55
【问题描述】:

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

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

【问题讨论】:

    标签: ios swift autolayout nslayoutconstraint


    【解决方案1】:

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

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

    let usernameTextField = UITextField()
    

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

    usernameTextField.heightAnchor.constraintEqualToConstant(30)
    

    然后为您的passwordTextField 重复此操作。

    【讨论】:

    • 非常感谢,它运行良好。我不知道你可以使用 = UITextField() 来初始化。
    猜你喜欢
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    相关资源
    最近更新 更多