2014-01-17 63 views
0

我目前手動定位我的用戶界面元素,如果我更新文本或添加元素會變得很煩人,因爲我必須每次重新計算所有位置。Autolayout - 以編程方式在空間中垂直排列元素?

是否有一種方法使用自動佈局來設置元素的大小和位置,例如如下所述,無論標籤包含多少文本?

UILabel (multiline, variable height) 
[20px gap] 
UILabel (multiline, variable height) 
[20px gap] 
UIButton 

回答

1

是的,它會是這個樣子

@implementation MyClass { 
    NSDictionary *_viewsDictionary; 
} 


- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
{ 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if (self) { 
     // First create your controls - you can just use CGRectZero 
     _label1 = [[UILabel alloc] initWithFrame:CGRectZero]; 
     _label1 setText:@"Some text"; 

     _label2 = [[UILabel alloc] initWithFrame:CGRectZero]; 
     _label2 setText:@"Some text 2"; 

     _button = [[UIButton alloc] initWithFrame:CGRectZero]; 

     // Then just add them to your as a sub view 
     [self addSubview:self.currentBalanceLabel]; 
     [self addSubview:_nameLabel]; 
     [self addSubview:_button]; 

     // Put them in an NSDictionary - this is a macro and will be used when setting up the contraints below 
     _viewsDictionary = NSDictionaryOfVariableBindings(_nameLabel, _currentBalanceLabel,_button); 

     // This tells the view to run update contraints 
     [self setNeedsUpdateConstraints]; 
     [self updateConstraintsIfNeeded]; 
    } 
} 


- (void)updateConstraints 
{ 
    [super updateConstraints]; 

    // Using the _viewsDictionary, we must tell always tell how all the controls will be setup both 
    // horizontally and vertically. In this case wear are going to tell the label to take the entire width 
    // The rest of the vies will be aligned on the left below 
    NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_label1]-|" 
                    options:0 
                    metrics:nil 
                    views:_viewsDictionary]; 

    //Add the contraints 
    [self addConstraints:constraints]; 

    // Next setup the vertical contraints. This is what you asked about spefically, label - 20 - label - 20 - button 
    constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_labelq]-20-[_label2]-20-[_button]" 
                  options: NSLayoutFormatAlignAllLeft 
                  metrics:nil 
                  views:_viewsDictionary]; 


    [self addConstraints:constraints]; 


} 

@end 
+0

爲了擴展這個有點:概念上發生了什麼事是,是的,你可以將它設置。爲此,需要在程序運行時手動更新項目的約束(vs僅使用Interface Builder中添加的約束)。上面的代碼是從一個在TableView中工作的應用程序獲取的。出於您的目的,重要的是在updateConstraints方法中創建約束。 –

+0

@ansible - 偉大的答案。謝謝! – fxfuture

相關問題