更改代码中的大小类(快速)

And*_*rei 3 ios swift size-classes adaptive-layout programmatically

我一直在尝试以纯代码(不使用情节提要)构建自适应布局并开始运行。我使用布局锚来设置约束,并利用traitCollectionDidChange方法在各种约束集和其他接口更改之间进行切换。我使用switch语句使用相应的约束集调用相应的方法。

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)

    switch (traitCollection.horizontalSizeClass, traitCollection.verticalSizeClass) {
    case (.regular, .regular):
        setupRegularRegular()

    case (.compact, .compact):
        setupCompactCompact()

    case (.regular, .compact):
        setupRegularCompact()

    case (.compact, .regular):
        setupCompactRegular()

    default: break
    }

}
Run Code Online (Sandbox Code Playgroud)

为了进行测试,我仅更改了一个约束,即centerYAnchor.constraint。在纵向模式中,常量为-150,在横向模式中,我希望将其更改为50。对于iPad,我将常量设置为0。

bigLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -150).isActive = true
Run Code Online (Sandbox Code Playgroud)

在iPhone和iPad之间切换时,效果很好。但是,如果您开始将iPhone从纵向旋转到横向,则布局系统将失败,并显示:

[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:0x600000097890 UILabel:0x7fac02c08aa0'Main Label'.centerY == UIView:0x7fac02e0a950.centerY - 150   (active)>",
"<NSLayoutConstraint:0x604000097840 UILabel:0x7fac02c08aa0'Main Label'.centerY == UIView:0x7fac02e0a950.centerY + 50   (active)>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x604000097840 UILabel:0x7fac02c08aa0'Main Label'.centerY == UIView:0x7fac02e0a950.centerY + 50   (active)>
Run Code Online (Sandbox Code Playgroud)

我尝试覆盖各种方法,并将约束的isActive属性设置为false,然后又设置为true,但这无济于事。我在网上搜索了几天。到目前为止没有解决方案。所以我的问题是,当旋转设备时,如何实际在尺寸等级之间切换?是否有必要重写任何其他方法或其他东西?是否有更好的纯代码自适应布局解决方案?关于自适应布局/大小类/布局锚点和代码约束(不使用情节提要),是否有最佳实践?感谢帮助!

PS设置约束的方法是:

func setupCompactRegular() {

    bigLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -150).isActive = true

}

func setupRegularCompact() {

    bigLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 50).isActive = true

}
Run Code Online (Sandbox Code Playgroud)

小智 5

问题是您正在创建新的约束。尝试保持对约束的引用并更改方法以更新它们

func setupCompactRegular() {

    self.bigLabelCenterYAnchor.constant = -150

}

func setupRegularCompact() {

    self.bigLabelCenterYAnchor.constant = 50

}
Run Code Online (Sandbox Code Playgroud)

layoutIfNeeded()如果没有自动更新,请在之后致电