如何在Swift中以编程方式在Horizo​​ntal行上设置约束?

时间:2017-12-04 06:28:27

标签: ios swift interface-builder ios-autolayout

如何在Swift中以编程方式在Horizo​​ntal行上设置约束? 我在"再试一次"按钮。那么,请告诉我如何在这一行设置约束。

代码是:

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

1 个答案:

答案 0 :(得分:1)

相应地更改常量的值。并确保在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))