【发布时间】:2014-07-03 07:03:48
【问题描述】:
我正在使用 UITableView 创建一个 Iphone 应用程序。在那我想改变相对于文本的单元格大小。我使用了以下代码。但它失败了。
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// CGRect screenBounds = [[UIScreen mainScreen] bounds];
// CGSize screenSize = screenBounds.size;
NSStringDrawingContext *ctx = [NSStringDrawingContext new];
NSAttributedString *aString = [[NSAttributedString alloc] initWithString:[message objectAtIndex:0]];
UITextView *calculationView = [[UITextView alloc] init];
[calculationView setAttributedText:aString];
CGRect textRect = [calculationView.text boundingRectWithSize:self.view.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:calculationView.font} context:ctx];
// CGSize size = [calculationView sizeThatFits:CGSizeMake(screenSize.width, FLT_MAX)];
return textRect.size.height;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"SimpleTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
[cell.textLabel setLineBreakMode:NSLineBreakByWordWrapping];
[cell.textLabel sizeToFit];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.imageView.image = [UIImage imageNamed:@"gg.jpg"];
cell.textLabel.text = [NSString stringWithFormat:[message objectAtIndex:0], indexPath.row];
return cell;
}
提前致谢。
【问题讨论】:
-
您可能想要 NSLog() textRect.size.height 值的高度以查看您得到的高度。您在视觉上看到了什么,您的单元格高度是否正确间隔但文本是单行?如果是,请尝试设置 cell.textLabel.numberOfRows = 0;否则,如果您愿意接受替代方法,我在这里使用 Autolayout 编写了一个演示应用程序:stackoverflow.com/questions/24478825/…
标签: ios iphone uitableview ios7