旋转设备时是否可以更改约束?如何才能做到这一点?
一个简单的例子可能是两个图像,在肖像中,一个堆叠在另一个之上,但在风景中是并排的。
如果这是不可能的,我还能如何完成这个布局呢?
我在代码中构造我的视图和约束,而不是使用接口生成器。
发布于 2013-12-03 18:29:00
我遵循与您相同的方法(没有nib文件或故事板)。您必须更新updateViewConstraints
方法中的约束(通过检查设备方向)。不需要在updateViewConstraints
中调用setNeedsUpdateConstraints
,因为只要更改设备方向,最后一个方法就会自动调用。
发布于 2020-02-12 03:12:17
对于正在搜索当前可能解决方案(Swift)的任何人,请在此UIViewController函数中更新您的约束:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {}
每次设备旋转时都会调用此函数。它允许您响应这些更改,甚至为它们添加动画。为了给你更好的概述,这就是我在上一个项目中如何通过改变两个子视图的约束来改变我的布局。在纵向模式下,我的子视图在彼此之上,而在横向模式下,子视图并排显示。
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
// 1. I recommend to remove existing constraints BEFORE animation, otherwise Xcode can yell at you "Unable to simultaneously satisfy constraints"
removeConstraintsOfSubview()
coordinator.animate(alongsideTransition: { [unowned self] context in
// 2. By comparing the size, you can know whether you should use portrait or landscape layout and according to that remake or add specific constraints
if size.height > size.width {
self.setPortraitLayout()
} else {
self.setLandscapeLayout()
}
// 3. If you want the change to be smoothly animated call this block here
UIView.animate(withDuration: context.transitionDuration) {
self.view.layoutIfNeeded()
}
}, completion: { _ in
// After the device is rotated and new constraints are added, you can perform some last touch here (probably some extra animation)
})
}
发布于 2013-07-21 21:59:42
您可以将约束保存到属性或变量,作为纵向和横向版本,然后在旋转时设置和删除它们。
我已经在xib中为初始视图设置了约束,并将它们分配给视图控制器中的出口。在旋转时,我创建替代约束,移除出口,但保留它们,插入替代。
反向旋转时的过程。
https://stackoverflow.com/questions/17772922
复制相似问题