2014-01-17 32 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

相关问题