【问题标题】:Auto Layout - UILabel inside UITableViewCell is not wrapping on initial load for iOS 6自动布局 - UITableViewCell 内的 UILabel 在 iOS 6 的初始加载时不换行
【发布时间】:2017-08-28 00:00:20
【问题描述】:

我发现 UILabel 包装在我的自定义 UITableViewCell 中时出现了一个奇怪的问题。我正在使用自动布局,虽然这在 iOS > 6 上运行良好,但 UILabel 内的 UITableViewCell 不会在 iOS 6 的第一次加载时包装。当我点击单元格并显示详细信息视图然后返回时,然后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;
}

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

【问题讨论】:

    标签: ios objective-c uitableview cocoa-touch autolayout


    【解决方案1】:

    尝试在您的代码中为您的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;
    }
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-29
      • 2017-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多