UItableviewcell中的多行UIlabel使用Autolayout

时间:2015-01-24 07:17:30

标签: ios iphone uitableview autolayout uilabel

我已将setMaXPreferredLayoutWidth设置为UILabel并将所有必需的约束添加到UIlabel现在我可以在UIlabel中看到多行UItableviewcell,但我的问题我是根据UIlabel值在MaxpreferredLayoutWidth的顶部和底部获得额外填充。

当我将MaxPreferreLayoutWidth设置为200时,我得到了这个 If maxPreferredLayoutwidth set to 200

当我将MaxPreferreLayoutWidth设置为100时,我得到了这个

MaxpreferredLayoutWidth  = 100

一般来说,UIlabel身高取决于preferredMaxLayoutWidth。 任何人都可以告诉我如何删除这个额外的填充并呈现UIlabel的确切高度?

3 个答案:

答案 0 :(得分:0)

试试这段代码,

CGSize suggestedSize = [textWithMultipleLines sizeWithFont:myLabel.font constrainedToSize:CGSizeMake(width, FLT_MAX) lineBreakMode:NSLineBreakByWordWrapping];//here "width" is the maximum acceptable width of myLabel
CGRect labelFrame = myLabel.frame;
labelFrame.size = suggestedSize;
[myLabel setFrame:labelFrame];

并在

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
{
     //get the string assigned to label
     CGSize suggestedSize = [stringAssignedToLabel sizeWithFont:myLabel.font constrainedToSize:CGSizeMake(width, FLT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
     return suggestedSize.height+5;
}

答案 1 :(得分:0)

最简单的方法是扩展自己的UITableViewCell类,并在那里创建一个UILabel,同时创建一个公共的getMethod:

  

接口:

- (CGFloat)getLabelHeight;
  

实现:

- (CGFloat)getLabelHeight {
  return label.frame.size.height
}
  

TableView文件:

-(CGFloat)heightForRowAtIndexPath {
    return [cell getLabelHeight]
}

- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath)indexPath {

   your_cell_instance = [[Your_Cell_Class alloc]initWithTableViewCellStyle:UITableViewCellStyleDefault andReuseID:your_reuse_id];

   your_cell_instance.text = @"Your Long Text"
   [your_cell_instance setNumberOfLines:0];
   [your_cell_instance sizeToFit];

   return your_cell_instance;

}

首先设置标签文本然后//行数和sizeToFit //

非常重要

您需要在适当的时间重新加载tableView数据

我没时间测试它,但我希望它有效。

答案 2 :(得分:0)

我们必须在计算heightForRowAtIndexPath中的单元格高度时设置tableview单元格框架 例如:

[tableViewCell setFrame:CGRectMake(0, 0, CGRectGetWidth(self.tableView.bounds), CGRectGetHeight(tableViewCell.bounds))];

然后在layoutSubviews的{​​{1}}方法中,我们必须设置UItableviewcell
例如:

preferredMaxLayoutwidth