轮换时如何避免约束冲突?

Posted

技术标签:

【中文标题】轮换时如何避免约束冲突?【英文标题】:How to avoid constraint conflicts during rotation? 【发布时间】:2019-08-28 14:18:35 【问题描述】:

我正在处理一个复杂的基于约束的布局,我需要有 2 个独立的纵向和横向布局。

在它们之间切换时,我遇到了冲突,因为纵向约束与横向约束不兼容,只能在大小更改后应用,但自动布局系统会尝试将旧约束应用于新大小(或其他)。

这在以下“玩具”示例中得到了展示:

import UIKit

class ViewController: UIViewController 
    var box: UIView!
    var activeConstraints: [NSLayoutConstraint] = []

    override func viewDidLoad() 
        super.viewDidLoad()
        self.view.accessibilityIdentifier = "ViewController"

        self.box = UIView()
        self.box.accessibilityIdentifier = "box"
        self.box.backgroundColor = UIColor.red
        self.box.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(self.box)

        self.box.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        self.box.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
        self.box.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
        self.box.widthAnchor.constraint(equalTo: self.box.heightAnchor).isActive = true

        let initialSize = self.view.bounds.size
        self.reactivateConstraints(forSize: initialSize)
    

    var portraitConstraints: [NSLayoutConstraint] 
        return [
            self.box.heightAnchor.constraint(lessThanOrEqualTo: self.view.heightAnchor)
        ]
    

    var landscapeConstraints: [NSLayoutConstraint] 
        return [
            self.box.heightAnchor.constraint(greaterThanOrEqualTo: self.view.heightAnchor)
        ]
    

    func reactivateConstraints(forSize size: CGSize) 
        NSLayoutConstraint.deactivate(self.activeConstraints)
        if size.width < size.height 
            self.activeConstraints = self.portraitConstraints
         else 
            self.activeConstraints = self.landscapeConstraints
        
        NSLayoutConstraint.activate(self.activeConstraints)
    

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) 
        super.viewWillTransition(to: size, with: coordinator)
        print("viewWillTransitionToSize")

        // HACK:
        //NSLayoutConstraint.deactivate(self.activeConstraints)

        coordinator.animate(alongsideTransition:  context in
            print("viewWillTransitionToSize - animateAlongsideTransition")
            self.reactivateConstraints(forSize: size)
            self.view.layoutIfNeeded()
        , completion: nil)
    

    override func viewWillLayoutSubviews() 
        super.viewWillLayoutSubviews()
        print("viewWillLayoutSubviews")
    


如果您从纵向开始并旋转,代码会产生以下输出:

viewWillLayoutSubviews
viewWillTransitionToSize
2019-08-28 16:04:22.067887+0200 TestALRotation[2484:12095036] [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:0x6000022ad130 H:|-(0)-[box](LTR)   (active, names: box:0x7fc12061b260, ViewController:0x7fc12061b460, '|':ViewController:0x7fc12061b460 )>",
    "<NSLayoutConstraint:0x6000022ad4a0 box.right == ViewController.right   (active, names: box:0x7fc12061b260, ViewController:0x7fc12061b460 )>",
    "<NSLayoutConstraint:0x6000022ad630 box.width == box.height   (active, names: box:0x7fc12061b260 )>",
    "<NSLayoutConstraint:0x6000022ad770 box.height <= ViewController.height   (active, names: box:0x7fc12061b260, ViewController:0x7fc12061b460 )>",
    "<NSLayoutConstraint:0x6000022836b0 'UIView-Encapsulated-Layout-Height' ViewController.height == 375   (active, names: ViewController:0x7fc12061b460 )>",
    "<NSLayoutConstraint:0x600002281130 'UIView-Encapsulated-Layout-Width' ViewController.width == 812   (active, names: ViewController:0x7fc12061b460 )>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x6000022ad630 box.width == box.height   (active, names: box:0x7fc12061b260 )>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.
viewWillLayoutSubviews
viewWillTransitionToSize - animateAlongsideTransition
viewWillLayoutSubviews

发生冲突,因为系统试图在不要求我的代码首先更新约束的情况下执行布局传递(冲突后打印 animateAlongsideTransition),因此纵向约束应用于新的横向大小(812x375),因此冲突发生了。

问题: 是否可以在不暂时禁用约束且不摆弄优先级的情况下以通用方式避免此类冲突? 我应该从哪里拨打reactivateConstraints() 以避免这种情况?

注意:我尝试将 reactivateConstraints() 移动到 coordinator.animate 调用之前,但这会产生另一个冲突,因为它会尝试将新约束应用于旧大小(这也是一个冲突)。

一些与此问题相关但没有答案的链接:

http://corsarus.com/2015/adaptive-layout-part-3-orientation-specific-layouts/ https://imnotyourson.com/ios-adaptive-layout-with-rotation-tips/ Correct way to programmatically update constraints when the device orientation changes?

【问题讨论】:

我认为问题出在您的约束开始... 不是尝试停用/激活。你期望这个布局做什么?在纵向启动时,您会看到一个限制为上/左/右的红色框,并且宽度 = 高度......因此,它填充了视图的上半部分(在 iPhone 8 上)。但是您希望它在旋转到横向时看起来像什么? 这是一个玩具示例。关键是您有一组仅适用于纵向的约束 A 和一组仅适用于横向的约束 B,以及切换它们的正确方法。实际上,我有一堆约束,而不仅仅是一个,理想情况下我希望它们不会引起冲突,而只是从一个集合平滑地更新到另一个集合。 要明确:我希望盒子总是方形的,纵向填充顶部(高度屏幕高度) . activeConstraints 不会导致布局更改,也不应该导致任何冲突。 【参考方案1】:

找到适合我的解决方案:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) 
    super.viewWillTransition(to: size, with: coordinator)
    print("viewWillTransitionToSize")

    self.view.setNeedsUpdateConstraints()


override func updateViewConstraints() 
    print("updateViewConstraints")
    self.reactivateConstraints(forSize: self.view.bounds.size)
    super.updateViewConstraints()

当设置setNeedsUpdateConstraints 标志时,系统会在大小更改后不久,但在布局通过之前调用updateViewConstraints,因此可以在那里激活新的约束,并且冲突消失了。

【讨论】:

以上是关于轮换时如何避免约束冲突?的主要内容,如果未能解决你的问题,请参考以下文章

发生约束冲突时如何调用触发器?

使用 docker 时如何避免“端口冲突”?

如何避免路由冲突?

当引用表中没有匹配的记录时,delete语句如何与REFERENCE约束冲突?

将数据从全局加载到共享内存时如何避免银行冲突

Git:如何避免在先前合并还原后合并功能分支时发生冲突