代码之家  ›  专栏  ›  技术社区  ›  user4806509

旋转设备时,约束不更新且视图为字母框

  •  -1
  • user4806509  · 技术社区  · 3 年前

    背景:

    myView

    在故事板上, centreX centreY 设置了约束条件。

    在守则中,, width height 约束是通过函数设置的 viewAddConstraints()

    旋转设备后,我呼叫 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)
    
    }
    

    图片:

    enter image description here

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

    enter image description here

    0 回复  |  直到 3 年前
        1
  •  2
  •   DonMag    3 年前

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

    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),
        ])
        
    }
    

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