2013-05-07 44 views
3

我想學習Autolayout,所以我正在通過教程閱讀,並與一些UIViews搞亂,看看我能讓他們做些什麼。我想知道如何通過自動佈局來完成從縱向到橫向的過渡,如下圖所示?例如,我認爲,如果我將黃色固定在視圖的頂部,藍色爲黃色,橙色爲藍色,橙色爲底部,則它們會按比例調整大小,並保持彼此之間的20個像素以及視圖的頂部和底部。但是,例如,藍色框不會讓我將它移到視圖的頂部,即使它固定在它上面的黃色視圖中,所以它會將所有內容都推下並從橫向屏幕中移出。我知道你可以平等地調整高度和寬度來調整大小,但是有什麼方法可以按比例調整大小,保持它們之間的距離嗎? enter image description hereiOS Autolayout按比例調整UIViews的大小?

回答

2

在界面構建器中製作約束可能令人沮喪,並且界面構建器還不能使用乘數來約束,如blue.height = red.height * 0.5。不過,它們在代碼中很容易製作。

我使用Interface Builder來創建和着色UIViews,所以首先我想刪除Interface Builder創建的所有約束。

// in UIViewController.m 
[self.view removeConstraints:self.view.constraints] ; 

我將創建一個使用constraintsWithVisualFormat:options:metrics:views:許多制約因素,所以我創建的指針到5個UIViews的字典,並創建一個NSMutableArray持有的約束。

NSDictionary* views = NSDictionaryOfVariableBindings(black, red, yellow, blue, orange) ; 
NSMutableArray* constraints = [NSMutableArray new] ; 

然後我創建一個定位UIViews,並表明具有相同的寬度&高度觀點的約束。

[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[black]-[yellow]-|" options:0 metrics:nil views:views]] ; 
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[red(==black)]-[blue(==yellow)]-|" options:0 metrics:nil views:views]] ; 
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[orange]-|" options:0 metrics:nil views:views]] ; 
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[black]-[red(==black)]-[orange]-|" options:0 metrics:nil views:views]] ; 
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[yellow]-[blue]-[orange]-|" options:0 metrics:nil views:views]] ; 

最後,我用乘法器創建約束,並添加所有約束。

[constraints addObject:[NSLayoutConstraint constraintWithItem:orange attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:black attribute:NSLayoutAttributeHeight multiplier:0.5 constant:0]] ; 
[constraints addObject:[NSLayoutConstraint constraintWithItem:yellow attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:black attribute:NSLayoutAttributeHeight multiplier:1.5 constant:0]] ; 
[constraints addObject:[NSLayoutConstraint constraintWithItem:yellow attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:black attribute:NSLayoutAttributeWidth multiplier:1.5 constant:0]] ; 
[self.view addConstraints:constraints] ; 
0

您可以按照以下步驟給出比例高度或寬度約束。

1)首先根據需要給出相等的高度或寬度約束。

2)雙擊右窗格中的約束或單擊約束右側的「編輯」。

3)像這樣改變乘數。如果從寬度100的視圖到寬度150的視圖添加了相等的寬度約束,則輸入乘數150:100。

4)您需要確保不會有關於此約束的任何警告,否則您需要更改乘數,如100:150。

5)發生這種情況是因爲有時當您給予等寬或高度約束時,第一個視圖將是視圖本身,有時第一個視圖將會是另一個視圖。這完全取決於您爲其他視圖設置的其餘約束條件。

6)現在當正確應用約束時應用其他約束並檢查。

謝謝。

相關問題