最佳答案
您可以通过代码实现这一点首先您必须为您的动态约束创建IBoutlet
Constant Constraint: // these constraint will remain same in both orientations
1- RedView top 到Superview的空间
2- RedView 到 Superview 的尾随空格
3- BlueView 引导空间到 Superview
4- BlueView bottom Space to SuperView
Dynamic Constraint
纵向约束:
1- RedView 高度
2- RedView 到 BlueView 的垂直空间
3- RedView 前导空间到 Superview
4- BlueView 到 Superview 的尾随空间
景观约束:
1- 红色 View 宽度
2- RedView水平空间到BlueView
3- RedView bottom Space to Superview
4- BlueView Top Space to Superview
现在您必须覆盖在方向更改时调用的方法
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animateAlongsideTransition({ (UIViewControllerTransitionCoordinatorContext) -> Void in
let orient = UIApplication.sharedApplication().statusBarOrientation
switch orient {
case .Portrait:
print("Portrait")
self.ApplyportraitConstraint()
break
// Do something
default:
print("LandScape")
// Do something else
self.applyLandScapeConstraint()
break
}
}, completion: { (UIViewControllerTransitionCoordinatorContext) -> Void in
print("rotation completed")
})
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
}
并调用这两个函数
Portrait Orientation Function
func ApplyportraitConstraint(){
self.view.addConstraint(self.RedViewHeight)
self.view.addConstraint(self.RedView_VerticalSpace_To_BlueView)
self.view.addConstraint(self.RedView_LeadingSpace_To_SuperView)
self.view.addConstraint(self.BlueView_TrailingSpace_To_SuperView)
self.view.removeConstraint(self.RedViewWidth)
self.view.removeConstraint(self.RedView_HorizontalSpace_To_BlueView)
self.view.removeConstraint(self.RedView_BottomSpace_To_SuperView)
self.view.removeConstraint(self.BlueView_TopSpace_To_SuperView)
}
LandScape Orientation Function
func applyLandScapeConstraint(){
self.view.removeConstraint(self.RedViewHeight)
self.view.removeConstraint(self.RedView_VerticalSpace_To_BlueView)
self.view.removeConstraint(self.RedView_LeadingSpace_To_SuperView)
self.view.removeConstraint(self.BlueView_TrailingSpace_To_SuperView)
self.view.addConstraint(self.RedViewWidth)
self.view.addConstraint(self.RedView_HorizontalSpace_To_BlueView)
self.view.addConstraint(self.RedView_BottomSpace_To_SuperView)
self.view.addConstraint(self.BlueView_TopSpace_To_SuperView)
}
希望它有助于通过编码通过布局管理来理解它。 如果您仍然无法理解,请检查我的代码
Github :
如果您有警告,只需将高度和宽度的约束优先级设置为 999。
关于ios - 纵向和横向模式下的不同布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34293073/