【问题标题】:Various autolayout constraints for different device orientations programmatically and without size classes?以编程方式和没有大小类的不同设备方向的各种自动布局约束?
【发布时间】:2016-03-17 12:18:20
【问题描述】:

这个问题和这个类似: 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];

或者你能建议一个更好的方法来解决这个问题吗?

【问题讨论】:

  • 你是如何创建它们的?正确的方法是要么修改某些约束,要么完全删除一些(或全部)并重新创建它们

标签: ios ios7 uiview autolayout constraints


【解决方案1】:

您可以在 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    相关资源
    最近更新 更多