为什么我不能使用自动布局创建多行UILabel?总是关闭

时间:2013-07-28 16:59:39

标签: ios objective-c uiview uilabel autolayout

我希望在我的UITextField底部有一个两行UILabel,作为免责声明。

我在viewDidLoad中有以下代码:

    UILabel *InstapaperSubscriptionLabel = [[UILabel alloc] init];

    InstapaperSubscriptionLabel.translatesAutoresizingMaskIntoConstraints = NO;
    InstapaperSubscriptionLabel.text = @"Requires an Instapaper subscription, please see the Instapaper website for more details.";
    InstapaperSubscriptionLabel.numberOfLines = 2;
    InstapaperSubscriptionLabel.lineBreakMode = NSLineBreakByWordWrapping;
    InstapaperSubscriptionLabel.preferredMaxLayoutWidth = self.view.bounds.size.width - 40;
    InstapaperSubscriptionLabel.textAlignment = NSTextAlignmentCenter;
    InstapaperSubscriptionLabel.backgroundColor = [UIColor clearColor];
    InstapaperSubscriptionLabel.textColor = [UIColor colorWithRed:112/255.0 green:112/255.0 blue:111/255.0 alpha:1.0];
    InstapaperSubscriptionLabel.font = [UIFont systemFontOfSize:14.0];

    [self.view addSubview:InstapaperSubscriptionLabel];

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:InstapaperSubscriptionLabel
                                                 attribute:NSLayoutAttributeTop
                                                 relatedBy:NSLayoutRelationEqual
                                                 toItem:self.passwordBox
                                                 attribute:NSLayoutAttributeBottom
                                                 multiplier:1.0
                                                 constant:15.0]];

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:InstapaperSubscriptionLabel
                                                 attribute:NSLayoutAttributeLeading
                                                 relatedBy:NSLayoutRelationEqual
                                                 toItem:self.view
                                                 attribute:NSLayoutAttributeLeft
                                                 multiplier:1.0
                                                 constant:20.0]];

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:InstapaperSubscriptionLabel
                                                 attribute:NSLayoutAttributeTrailing
                                                 relatedBy:NSLayoutRelationEqual
                                                 toItem:self.view
                                                 attribute:NSLayoutAttributeRight
                                                 multiplier:1.0
                                                 constant:20.0]];

但每次加载视图时,它看起来像这样:

enter image description here

它离屏幕一侧的位置。它为什么这样做?我希望它更集中。

1 个答案:

答案 0 :(得分:2)

我认为你在问题中显示的最后一个约束的常数应该是-20,而不是20。 您对该代码的评价是:

标签尾随=超级视图右侧* 1 + 20,它将标签的后缘20点偏离屏幕右侧。