如何在 Swift 中以编程方式对水平线设置约束?

How to set constraints on Horizontal line programmatically in Swift?

如何在 Swift 中以编程方式设置水平线的约束? 我在 "Try Again" 按钮中设置了这一行。那么,请告诉我如何在此行上设置约束。

代码是:

let hrzLine = UIView(frame: CGRect(x: 0, y: 647, width: 265, height: 1))

hrzLine.backgroundColor = UIColor.white

self.view.addSubview(hrzLine)

enter image description here

相应地更改常量的值。并确保你在 view.addSubview 之前声明 hrzline.translatesAutoresizingMaskIntoConstraints 就像我在下面所做的那样

   let hrzline = UIView()
   hrzLine.backgroundColor = UIColor.white

    hrzline.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubview(hrzLine)


    self.view.addConstraint(NSLayoutConstraint(item: hrzline, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: hrzline, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 265))
    self.view.addConstraint(NSLayoutConstraint(item: hrzline, attribute: .top, relatedBy: .equal, toItem: yourTryAgainButton, attribute: .top, multiplier: 1, constant: 10))
    self.view.addConstraint(NSLayoutConstraint(item: hrzline, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 10))