旋转后更改约束值

时间:2017-08-22 14:25:02

标签: ios swift nslayoutconstraint

我在viewDidLoad()

中使用此代码以编程方式将约束添加到视图中
let top = isLandscape ? 30.0 : 5.0
let bottom = isLandscape ? 60.0 : 20.0

let topConstraint = NSLayoutConstraint(item: mySubview, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: top)
let bottomConstraint = NSLayoutConstraint(item: mySubview, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: bottom)
let leadingConstraint = NSLayoutConstraint(item: mySubview, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 50.0)
let trailingConstraint = NSLayoutConstraint(item: mySubview, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: 50.0)

mySubview.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(mySubview)
self.view.addConstraints([topConstraint, bottomConstraint, leadingConstraint, trailingConstraint])

当设备方向改变时,如何应用适当的保护?我读到了有关setNeedsUpdateConstraints的内容,但不了解如何使用它,或者它是否能帮助我。

2 个答案:

答案 0 :(得分:2)

我认为这应该有所帮助:

override func willAnimateRotation(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
     self.view.setNeedsUpdateConstraints()
}

现在每次设备方向改变时,它都会重新计算约束并在必要时进行调整

答案 1 :(得分:0)

首先,为约束创建类级变量/属性。然后在viewDidLoad中,设置这些约束而不是创建新约束:

class MyViewController: UIViewController {

    var topConstraint = NSLayoutConstraint()
    var bottomConstraint = NSLayoutConstraint()
    var leadingConstraint = NSLayoutConstraint()
    var trailingConstraint = NSLayoutConstraint()
    var mySubView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()

        let top = isLandscape ? 30.0 : 5.0
        let bottom = isLandscape ? 60.0 : 20.0

        topConstraint = NSLayoutConstraint(item: mySubView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: top)
        bottomConstraint = NSLayoutConstraint(item: mySubView, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: bottom)

        leadingConstraint = NSLayoutConstraint(item: mySubview, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 50.0)
        trailingConstraint = NSLayoutConstraint(item: mySubview, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: 50.0)

        mySubview.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(mySubview)
        self.view.addConstraints([topConstraint, bottomConstraint, leadingConstraint, trailingConstraint])

    }
}

然后,当您想要更改值时:

    let top = isLandscape ? 30.0 : 5.0
    let bottom = isLandscape ? 60.0 : 20.0

    topConstraint.constant = top
    bottomConstraint.constant = bottom