ios - 如何避免旋转过程中的约束冲突?

标签 ios rotation autolayout nslayoutconstraint

我正在开发一个复杂的基于约束的布局,我需要有 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 调用之前,但这会产生另一个冲突,因为它尝试将新约束应用于旧尺寸(这也是一个冲突)。

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

最佳答案

找到了适合我的解决方案:

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,因此可以在那里激活新的约束,并且冲突消失了。

关于ios - 如何避免旋转过程中的约束冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57694538/

相关文章:

javascript - 与页面上的元素交互时防止滑动事件

JAVA - LWJGL - 纹理旋转

C# 从右角开始旋转 DrawString

ios - 如何在iPhone/iPad应用程序上以编程方式执行mov到mp4最快的“转储”?

ios - 在 iOS 中操作 XML 文件

ios - 可滚动 UITableView 作为覆盖层

autolayout - UILabel 子类 - 自定义 'drawRect' 方法导致文本被截断/不显示

ios - 使用多行 UILabel 自动调整自定义 View 的大小

ios - 使用图像展开 Segue

css - 如何获得清晰的 css 旋转文本?