旋转设备时约束不更新并且视图是信箱

Constraints not updating and view is letterboxed when rotating device

背景:

旋转设备时,视图 myView 变为信箱而不是调整大小以适合屏幕,请参见下图。

在故事板上,设置了 centreXcentreY 约束。

在代码中,widthheight 约束是使用函数 viewAddConstraints() 设置的,请参见下面的代码。

旋转设备后,我再次调用viewAddConstraints(),但Xcode给出以下错误:Unable to simultaneously satisfy constraints.


问题:

如何在设备旋转时正确删除旧约束,然后添加新约束?

如何在设备旋转时正确更新视图的约束?


代码:

func viewAddConstraints() {

// Width constraint full width of screen
        let myViewWidth = NSLayoutConstraint(item: myView as Any, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: view.bounds.width)
        myView.addConstraint(myViewWidth)

// Height constraint full height of screen
        let myViewHeight = NSLayoutConstraint(item: myView as Any, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: view.bounds.height)
        myView.addConstraint(myViewHeight)

}

图片:

当前情况,视图被错误地加了信箱。

预期情况,正确调整视图大小。

设置约束以使子视图“固定”在两侧的正确方法:

override func viewDidLoad() {
    super.viewDidLoad()
    
    let myView = UIView()
    myView.backgroundColor = .systemTeal
    myView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(myView)
    
    NSLayoutConstraint.activate([
        myView.topAnchor.constraint(equalTo: view.topAnchor),
        myView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        myView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
        myView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
    ])
    
}

或者,既然你应该尊重安全区

override func viewDidLoad() {
    super.viewDidLoad()
    
    let myView = UIView()
    myView.backgroundColor = .systemTeal
    myView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(myView)
    
    let g = view.safeAreaLayoutGuide

    NSLayoutConstraint.activate([
        myView.topAnchor.constraint(equalTo: g.topAnchor),
        myView.leadingAnchor.constraint(equalTo: g.leadingAnchor),
        myView.trailingAnchor.constraint(equalTo: g.trailingAnchor),
        myView.bottomAnchor.constraint(equalTo: g.bottomAnchor),
    ])
    
}

现在您的子视图将自动调整大小以适应设备旋转时的父视图。