9

我想根据宽度是否大于高度来更改布局。但我不断收到布局警告。我观看了两个关于自适应布局的 WWDC 视频,这对我有很大帮助,但并没有解决问题。我使用以下代码创建了一个简单版本的布局。这只是为了让人们可以重现我的问题。代码在 iPhone 7 plus 上运行。

import UIKit

class ViewController: UIViewController {

    var view1: UIView!
    var view2: UIView!

    var constraints = [NSLayoutConstraint]()

    override func viewDidLoad() {
        super.viewDidLoad()

        view1 = UIView()
        view1.translatesAutoresizingMaskIntoConstraints = false
        view1.backgroundColor = UIColor.red

        view2 = UIView()
        view2.translatesAutoresizingMaskIntoConstraints = false
        view2.backgroundColor = UIColor.green

        view.addSubview(view1)
        view.addSubview(view2)

        layoutPortrait()
    }

    func layoutPortrait() {
        let views = [
            "a1": view1,
            "a2": view2
        ]

        constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[a1]|", options: [], metrics: nil, views: views)
        constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[a2]|", options: [], metrics: nil, views: views)
        constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[a1(450)][a2]|", options: [], metrics: nil, views: views)
        NSLayoutConstraint.activate(constraints)
    }

    func layoutLandscape() {
        let views = [
            "a1": view1,
            "a2": view2
        ]

        constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[a1(a2)][a2(a1)]|", options: [], metrics: nil, views: views)
        constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[a1]|", options: [], metrics: nil, views: views)
        constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[a2]|", options: [], metrics: nil, views: views)
    NSLayoutConstraint.activate(constraints)
    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
         super.viewWillTransition(to: size, with: coordinator)

         NSLayoutConstraint.deactivate(constraints)

         constraints.removeAll()

         if (size.width > size.height) {
             layoutLandscape()
         } else {
            layoutPortrait()
         }

     } 

}

当我旋转几次时,xcode 会记录警告。我想我将布局切换到早期,因为它仍在变化,但我已经将纵向高度设置为大或其他东西。有人知道我做错了什么吗?

约束警告:(从横向返回纵向时发生)

[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x618000081900 V:|-(0)-[UIView:0x7ff68ee0ac40]   (active, names: '|':UIView:0x7ff68ec03f50 )>",
    "<NSLayoutConstraint:0x618000081d60 UIView:0x7ff68ee0ac40.height == 450   (active)>",
    "<NSLayoutConstraint:0x618000083cf0 V:[UIView:0x7ff68ee0ac40]-(0)-[UIView:0x7ff68ee0ade0]   (active)>",
    "<NSLayoutConstraint:0x618000083d40 V:[UIView:0x7ff68ee0ade0]-(0)-|   (active, names: '|':UIView:0x7ff68ec03f50 )>",
    "<NSLayoutConstraint:0x600000085d70 'UIView-Encapsulated-Layout-Height' UIView:0x7ff68ec03f50.height == 414   (active)>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x618000081d60 UIView:0x7ff68ee0ac40.height == 450   (active)>
4

5 回答 5

3

你是对的,你做的约束工作太早了。... 是系统创建的<NSLayoutConstraint:0x600000085d70 'UIView-Encapsulated-Layout-Height' UIView:0x7ff68ec03f50.height == 414对横向视图控制器视图高度的约束 - 为什么它是 414,恰好是 iPhone 5.5 (6/7 Plus) 横向高度。旋转尚未开始,垂直约束与 450 高度约束冲突,您会收到警告。

因此,您必须在旋转完成后添加约束。viewWillLayoutSubviews是合乎逻辑的地方,因为当视图大小准备好但屏幕上出现任何内容之前会调用它,并且可以保存系统它本来可以制作的布局传递。

但是,要使警告静音,您仍然需要删除viewWillTransition(to size: with coordinator:). 系统在调用之前会进行新的自动布局计算viewWillLayoutSubviews(),当从纵向变为横向时,您会收到相反的警告。

编辑:正如@sulthan 在评论中指出的那样,由于其他事情可以触发布局,您还应该始终在添加约束之前删除它们。如果[constraints]数组被清空,则没有效果。由于在停用后清空数组是一个关键步骤,它应该在自己的方法中,所以clearConstraints().

另外,请记住检查初始布局中的方向 - 您layoutPortrait()认为viewDidLoad()这当然不是问题。

新/更改方法:

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()

    // Should be inside layoutPortrait/Landscape methods, here to keep code sample short.
    clearConstraints() 

    if (self.view.frame.size.width > self.view.frame.size.height) {
        layoutLandscape()
    } else {
        layoutPortrait()
    }
}

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    clearConstraints()
}

/// Ensure array is emptied when constraints are deactivated. Can be called repeatedly. 
func clearConstraints() {
    NSLayoutConstraint.deactivate(constraints) 
    constraints.removeAll()
}
于 2017-01-19T03:36:37.390 回答
1

如果布局约束问题是由于与 a UIView-Encapsulated-Layout-Widthor约束冲突的固定(或以编程方式修改的)宽度或高度约束引起UIView-Encapsulated-Layout-Height的,则该不可破坏约束导致您的太大、必需(优先级 1000)约束被丢弃。

您可以通过简单地降低冲突约束的优先级(可能只是到 999)来经常解决问题,这将适应任何临时冲突,直到旋转完成并且后续布局将继续使用您需要的宽度或高度。

于 2019-02-16T19:36:31.793 回答
0

据我所知,警告实际上是因为约束移动得太晚了。旋转到横向时会出现警告 - 450 约束仍然设置并且无法满足,因为视图的高度太小。

我尝试了几件事,似乎效果最好的是在较小的视图上设置约束,这样较大的视图的高度仍然是 450。

而不是

constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[a1(450)][a2]|", options: [], metrics: nil, views: views)

我用了

let height = view.frame.height - 450
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[a1][a2(\(height))]|", options: [], metrics: nil, views: views)

然后在viewWillTransitionToSize

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    NSLayoutConstraint.deactivate(self.constraints)
    self.constraints.removeAll()

    coordinator.animate(alongsideTransition: { (context) in

        if (size.width > size.height) {
            self.layoutLandscape()
        } else {
            self.layoutPortrait()
        }
    }, completion: nil)

} 

编辑:

对我有用的另一件事(也许是更一般的答案,尽管我不确定是否推荐):在调用之前停用约束super.viewWillTransition,然后在过渡旁边为其余部分设置动画。我的理由是,从技术上讲,在旋转开始之前,约束被立即删除,因此一旦应用程序开始旋转到横向(此时旧的高度约束将无法满足),约束已经被停用,新的约束可以采用影响。

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        NSLayoutConstraint.deactivate(constraints)
        super.viewWillTransition(to: size, with: coordinator)
        constraints.removeAll()

        coordinator.animate(alongsideTransition: { (context) in
            if (size.width > size.height) {
                self.layoutLandscape()
            } else {
                self.layoutPortrait()
            }

        }, completion: nil)            
    } 
于 2017-01-17T18:33:25.283 回答
0

我想出了与@Samantha 大致相同的答案。但是,我不需要deactivate在调用 to 之前打电话super。这是使用特征集合的替代方法,但该transitionToSize方法的工作原理类似。

override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
    super.willTransition(to: newCollection, with: coordinator)
    NSLayoutConstraint.deactivate(constraints)

    constraints.removeAll()

    coordinator.animate(alongsideTransition: { context in
        if newCollection.verticalSizeClass == .compact {
            self.layoutLandscape()
        } else {
            self.layoutPortrait()
        }
    }, completion: nil)
}
于 2017-01-18T20:32:51.993 回答
0

这是有问题的部分:

constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[a1(450)][a2]|", options: [], metrics: nil, views: views)

此行生成 4 个约束:

  1. 从上到下a10
  2. 的高度a1450
  3. a1a2距离是0
  4. a2到底部的距离是0

这四个约束在横向模式下一起中断,因为屏幕的总高度将小于450.

您现在要做的是在更改为横向模式之前更新约束,并且在从纵向切换到横向时有效。但是,当您从横向切换到纵向时,您过早地更改了约束,并且在短时间内,您仍然处于横向时会遇到纵向约束,从而触发该警告。

请注意,您的约束本质上没有任何问题。如果您想修复警告,我认为最好的解决方案是降低您的其中一个约束的优先级,例如高度约束:

constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[a1(450@999)][a2]|", options: [], metrics: nil, views: views)
于 2017-01-18T21:05:08.340 回答