我一直在尝试以纯代码(不使用情节提要)构建自适应布局并开始运行。我使用布局锚来设置约束,并利用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 …Run Code Online (Sandbox Code Playgroud)