如何在Objective c中自动调整Tableviewcell中的标签?

时间:2017-01-03 13:24:29

标签: objective-c xcode tableview

我有一个像Facebook墙贴一样的单元格。

我的手机看起来像下图。

enter image description here

我希望根据从WebService收到的文本来调整我的单元格和文本标签。

我尝试了许多来自互联网的解决方案,但没有运气。

我试过的代码

- (CGFloat)tableView:(UITableView )tableView heightForRowAtIndexPath:    (NSIndexPath )indexPath
{

 CGSize maximumLabelSize = CGSizeMake(9999, FLT_MAX);

 CGSize expectedLabelSize = [label sizeWithFont:[UIFont fontWithName:@"Verdana" size:10] constrainedToSize:maximumLabelSize lineBreakMode:NSLineBreakByWordWrapping];


 [cellNewsimg.lblStatus sizeThatFits:expectedLabelSize];
cellNewsimg.lblStatus.frame.size.height=expectedLabelSize.height;
objtableviewNewsFeedback.rowHeight = UITableViewAutomaticDimension;
objtableviewNewsFeedback.estimatedRowHeight = 500;


cellNewsimg.lblStatus.frame.size expectedLabelSize;
return 350.0+200;

}

索引路径中行的单元格

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


NSArray *ary=[[NSBundle mainBundle] loadNibNamed:@"Newsfeed" owner:self options:nil];

cellNewsimg=(Newsfeed *)[ary firstObject];
cellNewsimg.lblStatus.text=label;

cellNewsimg.lblStatus.lineBreakMode =UILineBreakModeWordWrap;
cellNewsimg.lblStatus.numberOfLines = 0;
[cellNewsimg.lblStatus sizeThatFits:expectedLabelSize];
return cellNewsimg;
}

1 个答案:

答案 0 :(得分:0)

试试这个:

- (CGFloat)tableView:(UITableView )tableView heightForRowAtIndexPath:(NSIndexPath )indexPath  
{ 
  return [_tbl.dataSource tableView:tableView cellForRowAtIndexPath:indexPath].contentView.frame.size.height + 8;
}


- (UITableViewCell )tableView:(UITableView )tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 NSArray *ary=[[NSBundle mainBundle] loadNibNamed:@"Newsfeed" owner:self options:nil];
 cellNewsimg=(Newsfeed *)[ary firstObject];

 cellNewsimg.lblStatus.frame = CGRectMake(0,0,ScreenWidth,21); //set your x,y and Screenwidth is a float, set it dynamically as per your view

 cellNewsimg.lblStatus.text=label;

 cellNewsimg.lblStatus.lineBreakMode = NSLineBreakByWordWrapping;
 cellNewsimg.lblStatus.numberOfLines = 0;
 [cellNewsimg.lblStatus sizeToFit];  
 cell.contentView.frame = CGRectMake(0, 0, _tbl.frame.size.width, CGRectGetMaxY(cell.lblStatus.frame) + 8) ;

 return cellNewsimg;
}  

只需在cellForRowAtIndexPath:indexPath中获取标签尺寸,然后根据该设置设置所有控件。不要计算heightForRowAtIndexPath中的任何内容。

希望它有所帮助。