这种方法一般用于tableview,制作类似于微博浏览,空间展示动态的功能。表的高度根据图片以及字符串字数确定。
通过文字展示的最大宽度以及文字字体大小确定文字展示的高度
- (CGRect)getHeightOfText:(NSString *)text width:(CGFloat)width font:(UIFont *)font{
/*
width:设定的字符串展示的宽度
font :字符的字体大小
*/
CGRect rect = [text boundingRectWithSize:CGSizeMake(width, 0) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil];
/*
字符串对应高度
float aHeifht = rect.size.height;
字符串对应宽度
float aWidth = rect.size.width;
*/
return rect;
}
根据需要展示的图片高度或者文字高度自适应表行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if (文字内容){
NSString *text = [NSString stringWithFormat:@"\t%@",需要展示的文字];
CGRect rect = [self getHeightOfText:text width:300 font:[UIFont systemFontOfSize:14]];
return rect.size.height+10;
}else//展示图片
{
return [[图片 objectForKey:@"height"] integerValue]+10;//获取服务器中图片高度,为了美观都比原始高多10
}
}
设置cell内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NewsDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"data"];
NSDictionary *content = [_dataArray objectAtIndex:indexPath.row];
if ([[content objectForKey:@"data_type"] intValue] == 1) {
//文本
NSString *text = [NSString stringWithFormat:@"\t%@",[content objectForKey:@"content"]];
cell.txtLabel.text = text;
CGRect rect = [CommonTool getHeightOfText:text width:300 font:[UIFont systemFontOfSize:14]];
cell.txtLabel.frame = CGRectMake(10, 5, rect.size.width, rect.size.height);
}else{
//图片
NSString *urlString = [NSString stringWithFormat:@"%@%@",SERVER_ADDRESS,[[content objectForKey:@"image"] objectForKey:@"source"]];
[cell.newsImageView setImageWithURL:[NSURL URLWithString:urlString]];
cell.newsImageView.frame = CGRectMake(10, 5, 300, [[[content objectForKey:@"image"] objectForKey:@"height"] integerValue]);
}
return cell;
}