Autolayout - 以编程方式在空间之间垂直排列元素?

时间:2014-01-17 02:39:16

标签: ios user-interface uilabel frame autolayout

我目前正在手动定位我的UI元素,如果我更新文本或添加元素会很烦人,因为我每次都要重新计算所有位置。

有没有办法使用自动布局来调整元素的大小和位置,例如如下所示,无论标签包含多少文字?

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

1 个答案:

答案 0 :(得分: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