自动布局 - UITableViewCell 中的 UILabel 在 iOS 6 的初始加载时不会包装



我看到UILabel包装在我的自定义UITableViewCell中出现一个奇怪的问题。我正在使用自动布局,虽然这在 iOS> 6 上工作正常,但 iOS 6 首次加载时UITableViewCell内部的UILabel不会包装。当我点击单元格并显示详细信息视图然后返回时,UILabel 按预期结束。

以下是我向单元格添加标签的方式:

self.productNameLabel = [[UILabel alloc] init];
self.productNameLabel.translatesAutoresizingMaskIntoConstraints = NO;
self.productNameLabel.backgroundColor = [UIColor clearColor];
self.productNameLabel.textAlignment = NSTextAlignmentLeft;
self.productNameLabel.font = kFontDynamicSubHead;
self.productNameLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.productNameLabel.numberOfLines = 2;
[self.contentView addSubview:self.productNameLabel];

然后,我添加一些约束来定位标签。我没有设置任何高度/宽度约束。

最后,在我的单元格layoutSubviews中,我为我的标签设置了preferredMaxLayoutWidth

- (void)layoutSubviews {
    [super layoutSubviews];
    self.productNameLabel.preferredMaxLayoutWidth = self.productNameLabel.bounds.size.width;
}

如果有人以前遇到过这种情况或知道解决方法,那么请提出建议。

尝试在

代码中为UILabel添加约束,尝试为单元格添加此实现initWithCoder

-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self =  [super initWithCoder:aDecoder];
    if(self)
    {
        self.productNameLabel = [[UILabel alloc] init];
        self.productNameLabel.translatesAutoresizingMaskIntoConstraints = NO;
        self.productNameLabel.backgroundColor = [UIColor clearColor];
        self.productNameLabel.textAlignment = NSTextAlignmentLeft;
        self.productNameLabel.lineBreakMode = NSLineBreakByWordWrapping;
        self.productNameLabel.numberOfLines = 2;
        [self setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.contentView addSubview:self.productNameLabel];
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[view]-0-|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:@{@"view":self.productNameLabel}]];
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[view]-0-|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:@{@"view":self.productNameLabel}]];
        [self setNeedsLayout];
    }
    return self;
}

希望这有帮助

最新更新