好的,这就是我的困境,我有一块很好的代码块,它已被弃用,但它会计算任何文本块高度的合适大小。 (以下有效,但已弃用)
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0 && indexPath.row == 2) {
CGSize size = [[item desc] sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(290 - (10 * 2), 200000.0f)];
CGFloat height = MAX(size.height, 44.0f);
return height + (2 * 2);
}
return 44;
}
尝试删除已弃用的代码,因此我已经被困在正确的方法来修复它几天了,我想出了这个。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0 && indexPath.row == 2) {
NSStringDrawingContext *ctx = [NSStringDrawingContext new];
NSAttributedString *aString = [[NSAttributedString alloc] initWithString:[item desc]];
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];
CGFloat height = MAX(textRect.size.height, 44.0f);
return height + (2 * 2);
}
return 44;
}
这肯定不起作用,从代码级别的角度来看,它不会适当地调整单元格的大小。我觉得任何帮助都应该很容易。
答案 0 :(得分:1)
试试这个:
CGRect textRect = [calculationView.text boundingRectWithSize:CGSizeMake(290 - (10 * 2), 200000.0f)
options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:calculationView.font} context:ctx];
您没有提供所需的大小限制,因为您提供了弃用的方法。这就是为什么您没有获得所需的输出..
答案 1 :(得分:0)
只需编辑heightForRow方法,如:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0 && indexPath.row == 2)
{
NSStringDrawingContext *ctx = [NSStringDrawingContext new];
NSAttributedString *aString = [[NSAttributedString alloc] initWithString:[item desc]];
UITextView *calculationView = [[UITextView alloc] init];
[calculationView setAttributedText:aString];
[calculationView sizeToFit];
//CGRect textRect = [calculationView.text boundingRectWithSize:self.view.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:calculationView.font} context:ctx];
CGFloat height = calculationView.frame.size.height; //MAX(textRect.size.height, 44.0f);
NSLog(@"%.2f", calculationView.frame.size.height);
return height + (2 * 2);
}
return 44;
}