ios - UIScrollView 自动布局约束打破设备旋转

标签 ios cocoa-touch uiscrollview swift autolayout

我在 UIScrollView 及其 subview 上设置自动布局约束时遇到了一个相当烦人的问题。当设备方向发生变化时,它会打破约束并显示以下警告:

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.
(Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSLayoutConstraint:0x7a1b1830 V:[UIView:0x7a1b0520(768)]>",
    "<NSLayoutConstraint:0x7a1c5990 V:[UIView:0x7a1bcf50(1024)]>",
    "<NSLayoutConstraint:0x7a17aa70 V:|-(0)-[UIView:0x7a1b0520]   (Names: '|':UIScrollView:0x7a176520 )>",
    "<NSLayoutConstraint:0x7a1c49c0 V:[UIView:0x7a1b0520]-(0)-|   (Names: '|':UIScrollView:0x7a176520 )>",
    "<NSLayoutConstraint:0x7a172620 V:[UIView:0x7a1bcf50]-(0)-|   (Names: '|':UIScrollView:0x7a176520 )>",
    "<NSLayoutConstraint:0x7a172650 V:|-(0)-[UIView:0x7a1bcf50]   (Names: '|':UIScrollView:0x7a176520 )>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x7a1c5990 V:[UIView:0x7a1bcf50(1024)]>

我在 Storyboard中设置了一个 ScrollView ,它包含两个容器作为 subview 。 ScrollView 本身被固定在 super View 的所有四个边上(编辑器/固定/前导、尾随、顶部、底部空间到 super View )。这两个容器的边缘固定在具有自动布局约束的 ScrollView 上,但两者的宽度和高度都设置为固定在 Storyboard 上,请参见 att。图片:

enter image description here

两个容器的宽度和高度通过代码更新,一旦最初在 viewDidLoad() 中,每当设备方向改变时,在 didRotateFromInterfaceOrientation() 中:

    _primaryWidth.constant = view.bounds.size.width
    _primaryHeight.constant = view.bounds.size.height
    _secondaryWidth.constant = _primaryWidth.constant - 200
    _secondaryHeight.constant = _primaryHeight.constant

这是出现上述警告并且约束被打破并且布局过火的时候。有人能告诉我为什么会这样以及如何解决吗?

(请注意负 200。这是因为正确的容器应该具有更小的宽度。但这不会影响问题。没有这个约束就会收支平衡。)

最佳答案

你有约束将 ScrollView 的边缘固定到屏幕的边缘,这在纵向和横向上都有效。你还有一个约束将你的 View 之一的高度设置为 1024。

在纵向模式下一切正常,但是当您旋转到横向模式时,您不能将 1024 高度的东西固定到屏幕顶部和底部的边缘,因为屏幕只有 768 高度。一个必须离开,你可以看到哪个得到了斧头。

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x7a1c5990 V:[UIView:0x7a1bcf50(1024)]>

移除高度限制,你会没事的。无论如何你为什么需要它们?无论您给定的大小如何,您都希望 View 固定到屏幕/ super View 的边缘。非任意值还允许您在不更改布局的情况下将相同的代码/布局携带到其他设备或作为 subview 。

关于ios - UIScrollView 自动布局约束打破设备旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25644253/

相关文章:

iphone - UIScrollView和scrollRectToVisible :animated:

ios - UIScrollView 在 iOS7 中不滚动自动布局

ios - 在 iOS 上创建多列 View

ios - 我可以从 xcode 获取位置箭头、重新加载、搜索按钮吗?

iphone - iOS API 检测无线网络

ios - dequeueReusableCellWithIdentifier 为不同的 indexPath 返回相同的单元格

iphone - 文本输入框,类似于 iPhone 上的 SMS 应用程序

ios - 现有的 Xcode/Swift3 应用程序突然无法识别 Parse 框架

ios - 在当前应用中添加 UIPageViewController

ios - 在 iOS 11 中,键盘自动更正会创建无效的 UTF8