【发布时间】:2016-10-10 02:28:03
【问题描述】:
我正在展示一个视图控制器,就像 iPad 上我的主视图控制器的弹出窗口一样,它工作正常。但目前我正在将其 prefferedContentSize 设置为适合屏幕,因此当我旋转大小时不会自动调整大小。我需要弹出视图与主视图控制器中心对齐,纵向和横向宽度为 97%,高度为 90%。所以我现在尝试在我的 popupViewController 上添加自动布局约束,但不确定如何。以下是我到目前为止尝试过的代码。这给了我一个“NSInternalInconsistencyException”错误
#import "ViewController.h"
@interface ViewController ()
{
PopUpViewController *popUpController;
}
@end
- (IBAction)showPopUp:(UIButton *)sender {
popUpController = [[PopUpViewController alloc]initWithNibName:@"PopUpViewController" bundle:nil];
popUpController.view.center = self.view.center;
popUpController.view.layer.cornerRadius = 8.0f;
popUpController.view.layer.masksToBounds = YES;
popUpController.view.layer.borderWidth = 1.0f;
popUpController.view.layer.borderColor = [UIColor blueColor].CGColor;
popUpController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
popUpController.modalPresentationStyle = UIModalPresentationFormSheet;
// CGPoint frameSize = CGPointMake([[UIScreen mainScreen] bounds].size.width*0.97f, [[UIScreen mainScreen] bounds].size.height*0.9f);
// popUpController.preferredContentSize = CGSizeMake(frameSize.x, frameSize.y);
[self addConstraint];
[self.navigationController presentViewController:popUpController animated:YES completion:nil];
}
-(void)addConstraint
{
// Width constraint, half of parent view width
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:popUpController.view.superview
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeWidth
multiplier:0.97
constant:0]];
// Height constraint, half of parent view height
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:popUpController.view.superview
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeHeight
multiplier:0.9
constant:0]];
// Center horizontally
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:popUpController.view.superview
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0.0]];
// Center vertically
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:popUpController.view.superview
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterY
multiplier:1.0
constant:0.0]];
}
【问题讨论】:
-
为什么要向 self.view 添加约束,因为它是对子视图的引用。它不需要添加约束。当您添加任何视图作为 self.view 的子视图时,您需要添加约束
-
我展示的第二个视图控制器的高度和宽度没有调整大小。我应该怎么做才能调整大小?一种方法是在 viewwilltransition 上添加大小,但在制作动画时看起来并不漂亮。
标签: ios objective-c ipad autolayout nslayoutconstraint