使用autolayout在视图中居中UILabel内容

时间:2015-02-01 04:52:38

标签: ios autolayout

如果标签的内容居中,最好将标签的对齐方式设置为NSTextAlignmentCenter,还是将整个标签置于父视图的中心?

以下是我希望标签位于其父视图中的方式:

|  |                            |  |  
|  |       [ Label Text ]       |  |
|  |                            |  |

最外面的|是视图,内部|是contentView。

我正在创建内容视图和标签:

    _contentView = [[UIView alloc] init];
    _contentView.backgroundColor = [UIColor yellowColor];
    _contentView.translatesAutoresizingMaskIntoConstraints = NO;

    _titleLabel = [[UILabel alloc] init];
    _titleLabel.text = @"Hello world";
    _titleLabel.textAlignment = NSTextAlignmentLeft;
    _titleLabel.textColor = [UIColor blackColor];
    _titleLabel.backgroundColor = [UIColor orangeColor];
    _titleLabel.numberOfLines = 1;
    _titleLabel.translatesAutoresizingMaskIntoConstraints = NO;

视图的布局由自动布局控制:

- (void)setupConstraints {
    NSMutableArray *constraints = [NSMutableArray array];

    UIView *contentView = self.contentView;
    NSDictionary *viewsDict = NSDictionaryOfVariableBindings(contentView);
    NSArray *cn = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[contentView]-|"
                                                          options:0
                                                          metrics:nil
                                                            views:viewsDict];
    [constraints addObjectsFromArray:cn];

    cn = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-40-[contentView]"
                                                 options:0
                                                 metrics:nil
                                                   views:viewsDict];
    [constraints addObjectsFromArray:cn];

    UILabel *titleLabel = self.titleLabel;
    NSDictionary *viewsDict1 = NSDictionaryOfVariableBindings(titleLabel);
    cn = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[titleLabel]-|"
                                                 options:0
                                                 metrics:nil
                                                   views:viewsDict1];
    [constraints addObjectsFromArray:cn];

    viewsDict = NSDictionaryOfVariableBindings(titleLabel);
    cn = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[titleLabel]-|"
                                                 options:0
                                                 metrics:nil
                                                   views:viewsDict];
    [constraints addObjectsFromArray:cn];

    [self.view addConstraints:constraints];
}

我希望标签居中而不是左对齐,这是使用此代码生成的。

result

橙色是标签,黄色是内容视图。

0 个答案:

没有答案