2014-11-03 130 views
0

我試圖更好地理解自動佈局,並且創建了一些可以幫助我的靜態方法。現在我試圖在tableview結構中設置一個視圖數組(在行中)。這工作挺好。iOS自動佈局行

看到這裏我的問題:

enter image description here

要做到這一點我用這個代碼:

//In the update constraints method 
UIView *view1 = [self createView]; 
view1.backgroundColor = [UIColor redColor]; 
UIView *view2 = [self createView]; 
view2.backgroundColor = [UIColor yellowColor]; 

[self addSubview:view1]; 
[self addSubview:view2]; 

[self addConstraints:[DXVFL row:@[view1, view2] inView:self]]; 

//The row method 
+ (NSArray *) row:(NSArray const *)views inView:(UIView const *)superview { 
    NSMutableArray *constraints = [NSMutableArray new]; 
    CGFloat multiplier = 1.f/[views count]; 
    UIView *prev = nil; 

    for (UIView *view in views) { 
     if (!view.hidden) { 
      [constraints addObject:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeWidth multiplier:1.f constant:0.f]]; 
      [constraints addObject:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeHeight multiplier:multiplier constant:0.f]]; 

      if (prev) { 
       [constraints addObject:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:prev attribute:NSLayoutAttributeBottom multiplier:1.f constant:0.f]]; 
      } 

      prev = view; 
     } 

    } 
    return [constraints copy]; 
} 

所以這部分工作(我猜)。但是當我想要再次按行分割黃色視圖時。視圖總是添加到頂部區域?

在更新約束方法我這樣做:

UIView *view1 = [self createView]; 
view1.backgroundColor = [UIColor redColor]; 
UIView *view2 = [self createView]; 
view2.backgroundColor = [UIColor yellowColor]; 

[self addSubview:view1]; 
[self addSubview:view2]; 

UIView *view3 = [self createView]; 
UIView *view4 = [self createView]; 
[view2 addSubview:view3]; 
[view2 addSubview:view4]; 

[self addConstraints:[DXVFL row:@[view1, view2] inView:self]]; 
[view2 addConstraints:[DXVFL row:@[view3, view4] inView:view2]]; 

enter image description here

不過,我想在底部的兩行?我究竟做錯了什麼?

回答

0

關閉我的頭頂:

您需要添加一個約束來告訴它對準着眼於上海華頂。目前,您只需設置高度和寬度,但不要告訴它將頂端邊緣放在哪裏。

試着改變你的代碼如下:

if (!prev) { 
    [constraints addObject:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeTop multiplier:1.f constant:0.f]]; 
} else { 
    [constraints addObject:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:prev attribute:NSLayoutAttributeBottom multiplier:1.f constant:0.f]]; 
} 
+0

你是對的。 if(!prev)修復了我的問題,並將行正確放置在我想要的視圖中! – Haagenti 2014-11-04 14:41:39