【发布时间】:2023-04-05 12:21:01
【问题描述】:
我使用 Masonry 库来帮助以编程方式添加约束。 很好,但现在我面临的问题是,在用户将设备从横向旋转到纵向后,我需要卸载并添加新的约束。我尝试了相当“残酷”的解决方案,它确实改变了约束,但是,在几分之一秒内,我可以看到“旧”约束。用户旋转设备后是否有简单的方法来添加/删除约束?这就是我尝试过的(它有效,但正如我上面描述的那样,我可以在几分之一秒内看到“旧”帧):
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation)){
[bottomRight mas_updateConstraints:^(MASConstraintMaker *make) {
NSLog(@"We are on landscape");
make.top.equalTo(upperRight.mas_bottom).with.offset(20);
make.left.equalTo(self.view.mas_centerX).with.offset(20);
make.right.equalTo(bottomRightRight.mas_left).with.offset(-20);
make.bottom.equalTo(self.view.mas_bottom).with.offset(-100);
make.width.equalTo(bottomRightRight);
}]; }
else {
NSLog(@"Swapped");
[bottomRight mas_updateConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(upperRight.mas_bottom).with.offset(200);
make.left.equalTo(self.view.mas_centerX).with.offset(200);
make.right.equalTo(bottomRightRight.mas_left).with.offset(-200);
make.bottom.equalTo(self.view.mas_bottom).with.offset(-200);
make.width.equalTo(bottomRightRight);
}];
}
}
【问题讨论】:
-
didRotateFromInterfaceOrientation自 ios8 以来已被弃用。如果你没有支持 pre-ios8 的操作系统,你可以尝试使用- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection。可以激活和停用 NSLayoutConstraint,而不是添加和删除。我不知道 Masonry 是如何包装 NSLayoutConstraints 的,但是你可以在那里找到类比特征。
标签: ios autolayout masonry-ios-osx