【发布时间】:2014-07-02 00:17:39
【问题描述】:
我已成功调整 UITableViewCell 的大小以适应其内容,但我的 UILabel 未正确调整大小。这就是我调整单元格大小的方式:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *str = @"My really long text";
CGSize constrainedSize = CGSizeMake(250, 9999);
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:@"HelveticaNeue-Light" size:16.0], NSFontAttributeName,
nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:str attributes:attributesDictionary];
CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
if (requiredHeight.size.width > 250) {
requiredHeight = CGRectMake(0,0, 250, requiredHeight.size.height);
}
if (requiredHeight.size.height + 10 >= 60)
return requiredHeight.size.height + 10;
else
return 60;
}
我在 Storyboard 的原型单元格中创建了我的 UILabel
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Post-Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
UILabel *text = (UILabel *)[cell viewWithTag:2];
text.text = @"My Label's Text";
[text sizeToFit];
return cell;
}
【问题讨论】:
-
为什么我收到了反对票...
-
您如何将标签绑定到您的单元格?您能否确保当您更新单元格的框架时,内容视图的框架已更新?我通常将我的标签限制在内容视图中,因此更改它的框架会更改标签
-
@AlexReynolds 更新了我的答案,谢谢
-
height 方法中有很多可以改进的代码。
return MAX(60,requiredHeight.size.height + 10)。if(requiredHeigh.sie.width可以删除,因为它什么都不做。你能解释一下问题是什么吗?最简单的方法可能是包含它正在做什么的屏幕截图。 -
最后,标签是否会超过 1 行文本,因为有更好的方法来测量多行标签
标签: ios objective-c uitableview uilabel