2014-12-02 27 views
1

我正在嘗試以不同高度垂直居中2個視圖。使用* only *可視格式的中心視圖?

UILabel *view1 = [[UILabel alloc] init]; 
view1.backgroundColor = [UIColor redColor]; 
view1.text = @"view1\nline2"; 
view1.textAlignment = NSTextAlignmentCenter; 
view1.numberOfLines = 0; 
UILabel *view2 = [[UILabel alloc] init]; 
view2.backgroundColor = [UIColor greenColor]; 
view2.text = @"view2\nline2"; 
view2.textAlignment = NSTextAlignmentCenter; 
view2.numberOfLines = 0; 
[self.view addSubview:view1]; 
[self.view addSubview:view2]; 

NSDictionary *views = @{@"view1": view1, @"view2" : view2}; 

[self.view setTranslatesAutoresizingMaskIntoConstraints:NO]; 

for (UIView *view in views.allValues) { 
    [view setTranslatesAutoresizingMaskIntoConstraints:NO]; 
} 

[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[view1]-[view2(==view1)]-|" 
                    options:NSLayoutFormatAlignAllCenterY 
                    metrics:nil views:views]]; 
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(>=20)-[view1(200)]-(>=20)-|" 
                    options:NSLayoutFormatAlignAllCenterY 
                    metrics:nil views:views]]; 
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(>=20)-[view2(100)]-(>=20)-|" 
                    options:NSLayoutFormatAlignAllCenterY 
                    metrics:nil views:views]]; 

這使得兩個中心都垂直對齊,但它們位於超視圖的底部! enter image description here

我想垂直中心不僅相對於彼此,也在超視圖。

我說像這樣的約束,它的工作原理:

[self.view addConstraint: 
[NSLayoutConstraint constraintWithItem:view1 
           attribute:NSLayoutAttributeCenterY 
           relatedBy:NSLayoutRelationEqual 
           toItem:self.view 
           attribute:NSLayoutAttributeCenterY 
          multiplier:1 
           constant:0]]; 

enter image description here

但我想知道,這是可能實現只用視覺形式?

+0

我使用PureLayout來處理這類事情。 – elkraneo 2014-12-02 20:57:05

回答

2

是的,這是可能的,但只能通過添加spacer視圖。所以,如果你創建一對夫婦的意見,讓我們給他們打電話spacer1和spacer2,你可以居中廠景與此字符串,

@"V:|[spacer1][view1][spacer2(==spacer1)]|" 

這假定廠景有一個固定的高度。我不會推薦這樣做,但我只是使用您在帖子底部顯示的代碼。

+0

好吧,我明白了。看來視覺格式非常有限。所以它應該與「傳統」約束相結合。 – Ixx 2014-12-03 08:45:56

0

如何計算「度量」中的Y?

[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-centerY-[view1(200)]-(>=20)-|" 
                    options:NSLayoutFormatAlignAllCenterY 
                    metrics:@{@"centerY": @(CGRectGetHeight(self.view.frame)/2.0 - 100)} 
                    views:views]]; 
+1

這種方法的問題是,當你旋轉視圖時,它不起作用,除非你把它放在它將被更新的地方(然後你必須先移除舊的)。 – rdelmar 2014-12-02 21:11:24

+0

也許將它與Size類混合? – elkraneo 2014-12-02 21:12:20

+0

我不這麼認爲。最好是堅持使用constraintWithItem ... – rdelmar 2014-12-02 21:13:32