将文本字段限制为 Swift 中的按钮

Constraining Text Field to Button in Swift

我在故事板中创建了一个按钮,但有一个需要在代码中实现的自定义 UITextField,我试图放置文本字段,使其位于按钮上方 20 像素处,但我没有得到出于某种原因想要的结果。我是不是遗漏了什么,或者这不是您实施它的方式?这是我的实现和输出:

@IBOutlet weak var buyPointsButton: UIButton!

lazy var cardTextField: STPPaymentCardTextField = {
    let cardTextField = STPPaymentCardTextField()
    return cardTextField
}()

viewDidLoad

self.view.addSubview(cardTextField)
cardTextField.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
    NSLayoutConstraint(item: cardTextField, attribute: .bottom, relatedBy: .equal, toItem: buyPointsButton, attribute: .top, multiplier: 1, constant: 70),
    NSLayoutConstraint(item: cardTextField, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: buyPointsButton.frame.width),
    NSLayoutConstraint(item: cardTextField, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1, constant: 0),
    NSLayoutConstraint(item: cardTextField, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 28)
])

主要问题是您将文本字段的 .centerY 设置为视图的 .centerY 您将文本字段的底部限制在按钮的顶部...

如果您使用更“现代”的语法,您会发现 更容易处理约束,并包含告诉自己约束是什么的注释 - 或者至少,应该 - 做。

例如:

override func viewDidLoad() {
    super.viewDidLoad()

    self.view.addSubview(cardTextField)
    cardTextField.translatesAutoresizingMaskIntoConstraints = false
    
    NSLayoutConstraint.activate([
        
        // Bottom of text field 20-points above Top of button
        cardTextField.bottomAnchor.constraint(equalTo: buyPointsButton.topAnchor, constant: -20.0),
        
        // text field Width equal to button Width
        cardTextField.widthAnchor.constraint(equalTo: buyPointsButton.widthAnchor),
        
        // text field centered horizontally to button
        cardTextField.centerXAnchor.constraint(equalTo: buyPointsButton.centerXAnchor),
        
        // text field Height equal to 28
        cardTextField.heightAnchor.constraint(equalToConstant: 28.0),
        
    ])
}