2013-02-11 55 views
1

我正在研究這個iPad應用程序,我正在考慮使用自動佈局來讓我的生活更輕鬆。我創建了這個側欄控件,允許用戶切換到不同的頁面(就像標籤欄控制器一樣,但這是在iPad的左側)。現在在橫向我希望這個視圖的寬度是256像素,但是當iPad處於縱向時,我希望這個視圖的寬度爲100像素。如何根據界面方向使用自動佈局來固定視圖的寬度?用故事板和自動佈局修正縱向和橫向方向的視圖寬度?

回答

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]; 
} 
+0

你好,這似乎是工作,但是當我旋轉,第一次我碰到下面的調試消息:無法同時滿足的約束。 ... ( 「」, 「」 ) 將嘗試通過打破約束來恢復 gossainapps 2013-02-12 00:34:13

+0

在刪除寬度限制之前再次添加它嗎?有兩個固定寬度的矛盾衝突。即100和256寬度。 – railwayparade 2013-02-12 00:40:20

+0

好吧,我把它修好了。而不是調用[self.view removeConstraint:self.widthConstraint];我不得不調用[self.leftColumnContainerView removeConstraint:self.widthConstraint]; – gossainapps 2013-02-12 00:50:07

相關問題