1

我正在开发这个 iPad 应用程序,我正在考虑使用自动布局来让我的生活更轻松。我创建了这个侧栏控件,它允许用户切换到不同的页面(就像标签栏控制器一样,但它位于 iPad 的左侧)。现在在横向我希望这个视图的宽度为 256 像素,但是当 iPad 处于纵向时我希望这个视图的宽度为 100 像素。如何根据界面方向使用自动布局来固定视图的宽度?

4

1 回答 1

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];
}
于 2013-02-11T23:56:32.700 回答