【问题标题】:Unable to autosize the label inside the UITableView in iOS?无法在 iOS 中自动调整 UITableView 内的标签大小?
【发布时间】:2015-10-12 13:58:26
【问题描述】:

我在UITableCell 中添加了一个标签。现在标签可以具有基于服务器响应的动态内容。所以我想根据标签中的内容来设置标签的高度。当文本增加时,它应该是多行。到目前为止,我已经尝试了这些,但没有任何效果。

cell.label_like_count.lineBreakMode = NSLineBreakByWordWrapping;
cell.label_like_count.numberOfLines = 0;
[cell.label_like_count sizeToFit];
NSString *first_like_user=@"Some Name rtyrtytyt";
int count=[first_like_user length];
NSString *like_count=@"12";
like_count=[like_count stringByAppendingString:@" others like your post"];
first_like_user=[first_like_user stringByAppendingString:@" and "];
first_like_user=[first_like_user stringByAppendingString:like_count];
NSMutableAttributedString *mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:first_like_user];

NSAttributedString *attributeStr = [[NSAttributedString alloc]initWithString:@"\n" attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]}];

[mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)];

[mutableAttributeStr appendAttributedString:attributeStr];

cell.label_like_count.attributedText = mutableAttributeStr;
CGSize maximumLabelSize = CGSizeMake(187,9999);
CGSize requiredSize = [cell.label_like_count sizeThatFits:maximumLabelSize];
CGRect labelFrame = cell.label_like_count.frame;
labelFrame.size.height = requiredSize.height;
cell.label_like_count.frame = labelFrame;

[cell.label_like_count setAttributedText:mutableAttributeStr];

【问题讨论】:

  • 给标签提供宽度约束和换行符作为自动换行!!!
  • 我已经换行了
  • 你还需要增加你的 UITableviewcell 高度。
  • 有人能给我建议一下具体的代码吗?
  • 您必须将 UILabel 上的 preferredMaxLayoutWidth 设置为您希望文本换行的区域的宽度。如果您使用自动布局,您只需要适当的约束和此属性集因为应该自动计算高度。所以你应该做的就是创建单元格,设置单元格属性和自动布局应该做剩下的事情。如果它不起作用,那么您的约束可能不正确。

标签: ios objective-c iphone uitableview ipad


【解决方案1】:

iOS8 及以上:

  1. 为单元格的内容视图添加标签
  2. 所有标签的边缘对齐到内容的视图边缘
  3. 设置label.numberOfLines = 0;
  4. 设置self.tableView.rowHeight = UITableViewAutomaticDimension;
  5. 设置self.tableView.estimatedRowHeight = your_cell_average_height;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 2012-03-26
    • 2018-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多