我正在研究这个iPad应用程序,我正在考虑使用自动布局来让我的生活更轻松。我创建了这个侧栏控件,允许用户更改为不同的页面(就像标签栏控制器,但这是在iPad的左侧)。现在处于横向方向,我希望此视图的宽度为256像素,但当iPad处于纵向方向时,我希望此视图的宽度为100像素。如何根据界面方向使用自动布局来固定视图的宽度?
答案 0 :(得分:1)
您可以使用 updateViewConstraints 调用来修改方向更改时的布局。
以下示例以编程方式创建视图,但您可以在界面构建器中连接侧边栏的宽度约束以实现相同的目的。
例如:
//create a custom view using autolayout, this is the equivalent of you side bar
- (void)viewDidLoad{
[super viewDidLoad];
//create a custom view
[self.view setTranslatesAutoresizingMaskIntoConstraints:NO];
UIView *vw=[[UIView alloc] init];
self.customView =vw;
self.customView.backgroundColor = [UIColor blackColor];
[self.customView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:self.customView];
NSArray *arr;
//horizontal constraints
arr = [NSLayoutConstraint constraintsWithVisualFormat:@"|-20-[vw]"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(vw)];
[self.view addConstraints:arr];
//vertical constraints
arr = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[vw(200)]"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(vw)];
[self.view addConstraints:arr];
}
- (void)updateViewConstraints{
[super updateViewConstraints];
//remove the existing contraint
if(self.widthConstraint!=nil){
[self.view removeConstraint:self.widthConstraint];
}
//portait set width to 100
if(UIInterfaceOrientationIsPortrait(self.interfaceOrientation)){
self.widthConstraint = [NSLayoutConstraint constraintWithItem:self.customView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:0
multiplier:1.0
constant:100.0];
}
//landscape set width to 256
else{
self.widthConstraint = [NSLayoutConstraint constraintWithItem:self.customView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:0
multiplier:1.0
constant:256.0];
}
[self.view addConstraint:self.widthConstraint];
}