假设您已经在处理方向并且正确接收事件,我认为最好创建双重约束并操纵它们的优先级。
在情节提要中,将按钮放在其中一个位置并添加所需的所有约束。将所有的优先级设置为 900(稍后会解释为什么不是 1000)并确认布局正常。
现在将这些约束优先级设置为 100 并开始为其他布局添加约束。将这些约束优先级设置为 900,并确认布局也适用于此场景。
此时,您需要将一组的优先级更改为 900,将其他设置为 100 以交换模式。所以现在开始编码......
您将需要这些约束的出口,拖拽所有这些约束、命名它们并添加然后更改每个约束的优先级会很痛苦。但幸运的是,您可以为此使用数组,因此在您的代码中添加以下内容:
@IBOutlet var portraitConstraints: [NSLayoutConstraint]?
@IBOutlet var landscapeConstraints: [NSLayoutConstraint]?
现在只需将所有约束拖到这 2 个数组中作为出口。
剩下的就很简单了。就像是:
func setMode(mode: LayoutMode, animated: Bool) {
switch mode {
case .portrait:
portraitConstraints?.forEach { $0.priority = 900 }
landscapeConstraints?.forEach { $0.priority = 100 }
case .landscape:
portraitConstraints?.forEach { $0.priority = 100 }
landscapeConstraints?.forEach { $0.priority = 900 }
}
UIView.animate(withDuration: animated ? 0.3 : 0.0) {
self.view.layoutIfNeeded()
}
}
关于不将约束优先级设置为 1000:
不允许更改优先级设置为 1000 的约束的优先级。不知道为什么,不在乎为什么。
编辑:这似乎不清楚所以让我给你举一个例子:
假设您有一个包含“Mobile”、“1”、“20.00KD”、“-/+”的视图,称为inputContainer
,删除按钮称为deleteButton
,左侧的图像视图称为imageView
。
现在,您将在纵向模式下将约束设置为:
inputContainer.top = superView.top + t
inputContainer.leading = imageView.trailing + a
deleteButton.leading = inputContainer.leading
deleteButton.top = inputContainer.bottom + b
deleteButton.bottom = superView.bottom - t
然后在风景中,您将拥有:
inputContainer.center.y = superView.center.y
inputContainer.leading = imageView.trailing + a
deleteButton.center.y = switchView.center.y
deleteButton.leading = inputContainer.trailing + b
现在在故事板中将其中一个设置为 900 的优先级,将其他设置为 100。然后将所有这些约束连接到代码中的适当数组中。这就对了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句