ios - 以编程方式且没有尺寸类别的不同设备方向的各种自动布局约束?

标签 ios ios7 uiview autolayout constraints

这个问题和这个类似: Autolayout and Device Orientation

但是 updateViewConstraints 永远不会被调用(因为旋转时没有调用提到的方法,在 iOS 9.1 模拟器上测试)。一般来说,这个主题似乎不包含正确答案或答案太旧。

我不能使用大小类,因为该项目也应该支持 iOS 7,它支持大小类,但有很大的限制。

看来我需要清除并重新创建每个旋转事件的所有约束:

1)哪个方法应该重新创建约束?

2) 如何重新创建它们?也许我错误地删除了它们:

for (UIView *v in self.view.subviews)
{
    v.translatesAutoresizingMaskIntoConstraints = NO;
}
for (UIView *v in self.view.subviews)
{
    [v removeConstraints:v.constraints];
    [self.view removeConstraints:v.constraints];
}
[self.view removeConstraints:self.view.constraints];

或者您能否建议解决此问题的更好方法?

最佳答案

您可以在 viewDidLoad 上以编程方式创建两组不同的约束,并且只激活您想要使用的那些

myPortraitConstraint = NSLayoutConstraint(item: someItem, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1.0, constant: 10
myPortraitConstraint.active = true

myLandscapeConstraint = NSLayoutConstraint(item: someItem, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1.0, constant: 0
myLandscapeConstraint.active = false

然后在旋转事件上切换您希望使用的约束

myPortraitConstraint.active = false
myLandscapeConstraint.active = true
self.view.layoutIfNeeded()

关于ios - 以编程方式且没有尺寸类别的不同设备方向的各种自动布局约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34226018/

相关文章:

ios - Objective-C 中的复合语句

ios - 多行 NSAttributed 字符串作为 UIButton 标题

ios - 从文本字段中移除焦点

ios - Swift 无法更改 xib uiview 中的 ImageView 框架

ios - 更改 UIView 框架

ios - 字符串中的表情符号数量?

ios - Swift 4 中带有返回 bool 的 UIAlertView 共享类

iOS 7 UIToolBar 覆盖状态栏

ios - 没有 NIB,UIWindow 没有填满屏幕,iOS 7

xml - 无法加载带有 UICollectionVIewCell 数据的 UIView