ios7 - boundingRectWithSize:boundingSize 不返回所需的标签高度
Posted
技术标签:
【中文标题】ios7 - boundingRectWithSize:boundingSize 不返回所需的标签高度【英文标题】:ios7 - boundingRectWithSize:boundingSize not returning the needed label height 【发布时间】:2013-12-19 16:56:55 【问题描述】:我正在尝试在 tebleview 中调整我的自定义单元格的大小。但没有成功。 最后的NSlog返回:
2013-12-19 18:51:40.785 DevCloud[15750:70b] 20.281000
2013-12-19 18:51:40.786 DevCloud[15750:70b] 41.565002
2013-12-19 18:51:40.787 DevCloud[15750:70b] 20.281000
2013-12-19 18:51:40.787 DevCloud[15750:70b] 41.565002
这是我的 2 个单元格和单元格高度的方法实现: 如何让它发挥作用? :)
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
static NSString *CellIdentifier = @"TimelineCell";
TLRKTimelineCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
cell.sampleLabel.text = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer fermentum, neque sed viverra vestibulum, arcu ligula imperdiet turpis, blandit consectetur quam neque eu urna. Duis rhoncus accumsan eleifend. Vestibulum ac nunc aliquet, semper felis at, suscipit tortor. Etiam nec mauris nunc.";
return cell;
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
TLRKTimelineCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TimelineCell"];
CGSize boundingSize = CGSizeMake(cell.sampleLabel.frame.size.width, FLT_MAX);
UIFont *font = [UIFont fontWithName:@"Helvetica Neue" size:17];
CGRect textRect = [cell.sampleLabel.text boundingRectWithSize:boundingSize options:NSStringDrawingUsesFontLeading attributes: @NSFontAttributeName:font context:nil];
NSLog(@"%f",textRect.size.height);
NSLog(@"%f",textRect.size.width);
return textRect.size.height;
【问题讨论】:
【参考方案1】:我认为问题在于方法heightForRowAtIndexPath
在cellForRowAtIndexPath
之前被调用。
在heightForRowAtIndexPath
中,您应该将NSArray
传递给indexPath.row
,在这种情况下,我写了您的cell.textLabel.text
,它应该可以工作:
...
NSString *string = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer fermentum, neque sed viverra vestibulum, arcu ligula imperdiet turpis, blandit consectetur quam neque eu urna. Duis rhoncus accumsan eleifend. Vestibulum ac nunc aliquet, semper felis at, suscipit tortor. Etiam nec mauris nunc.";
CGRect textRect = [string boundingRectWithSize:boundingSize options:NSStringDrawingUsesFontLeading attributes: @NSFontAttributeName:font context:nil];
...
我建议将:NSStringDrawingUsesFontLeading
更改为:NSStringDrawingUsesLineFragmentOrigin
【讨论】:
是的 :) 我自己修这些 :)。以上是关于ios7 - boundingRectWithSize:boundingSize 不返回所需的标签高度的主要内容,如果未能解决你的问题,请参考以下文章