我需要在旋转设备时更改视图的高度。我正在storyboard
使用autolayout
,我在视图控制器中将高度约束设置为IBOutlet
:
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *passwordViewHeight;
然后,在视图控制器中我也有方法:
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context)
{
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
[self.view setNeedsUpdateConstraints];
} completion:^(id<UIViewControllerTransitionCoordinatorContext> context)
{
}];
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
}
- (void)updateViewConstraints
{
[super updateViewConstraints];
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (orientation == UIInterfaceOrientationPortrait) {
[self.welcomeLabel setHidden:NO];
[self setAllPortraitConstraints];
}
else if ((orientation == UIInterfaceOrientationLandscapeLeft) ||
(orientation == UIInterfaceOrientationLandscapeRight)) {
[self.welcomeLabel setHidden:YES];
[self setAllLandscapeConstraints];
}
}
- (void)setAllLandscapeConstraints
{
[self.view removeConstraint:self.passwordViewHeight];
// More constraints
self.passwordViewHeight = [NSLayoutConstraint constraintWithItem:self.passwordView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0
constant:34.0];
// More constraints
[self.view addConstraint:self.passwordViewHeight];
// More constraints
}
- (void)setAllPortraitConstraints
{
[self.view removeConstraint:self.passwordViewHeight];
// More constraints
self.passwordViewHeight = [NSLayoutConstraint constraintWithItem:self.passwordView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0
constant:40.0];
// More constraints
[self.view addConstraint:self.passwordViewHeight];
// More constraints
}
然后,当我以纵向方式运行应用程序并将设备旋转到横向时,我会在Xcode
中显示此登录信息:
无法同时满足约束条件。 可能至少下列列表中的一个约束是您不想要的约束。试试这个:(1)看看每个约束并试着找出你不期望的东西; (2)找到添加了不需要的约束或约束的代码并修复它。 (注意:如果你看到你不理解的NSAutoresizingMaskLayoutConstraints,请参阅UIView属性的文档translatesAutoresizingMaskIntoConstraints)
(
"id: login.1, constant: 40.000000",
"id: (null), constant: 34.000000"
)
将尝试通过违反约束来恢复 id:login.1,常量:40.000000
我想替换约束,在设备方向改变时给它一个新的常量,我做错了什么?
提前致谢
答案 0 :(得分:0)
尝试在
试试这个:loadView
或某些初始化代码中创建约束。然后将您的代码更改为:
- (void)setAllLandscapeConstraints
{
self.passwordViewHeight.constant = 34;
}
- (void)setAllPortraitConstraints
{
self.passwordViewHeight.constant = 40;
}