heightForRowAtIndexPath:当字符串包含换行符\ n时,错误的计算

时间:2012-10-30 15:41:42

标签: ios uitableview nsstring heightforrowatindexpath

我在分组UITableViewCell中插入了以下字符串:

NSString = @"In 1879, Steve Dancy sells his New York shop and ventures west to explore and write a journal about his adventures. Though he's not looking for trouble, Dancy's infatuation with another man's wife soon embroils him in a deadly feud with Sean Washburn, a Nevada silver baron.\n\nInfuriated by the outrages of two hired thugs, the shopkeeper kills both men in an impulsive street fight. Dancy believes this barbarian act has closed the episode. He is wrong. He has interfered with Washburn's ambitions, and this is something the mining tycoon will not allow.\n\nPinkertons, hired assassins, and aggrieved bystanders escalate the feud until it pulls in all the moneyed interests and power brokers in Nevada. Can the former city slicker settle accounts without losing his life in the process?"

请注意它包含\ n。当字符串包含新行时,我在heightForRowAtIndexPath:方法中返回了不正确的高度:

#define FONT_SIZE 14.0f
#define CELL_CONTENT_MARGIN 14.0f

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; {
    CGSize constraint = CGSizeMake(CGRectGetWidth(self.view.frame) - (CELL_CONTENT_MARGIN * 2), 20000.0f);
    CGSize size = [self.giftProduct.productDescription sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
    CGFloat height = MAX(size.height, 44.0f);
    return height + (CELL_CONTENT_MARGIN * 2);
}

其他不包含新行的字符串工作正常。是否有理由在计算高度时不考虑新线并且对我的返回距离太短?

由于

1 个答案:

答案 0 :(得分:0)

发布的代码运行正常并提供正确的结果。问题必须在其他地方。

也许self.view.frame的宽度与UITableView的界限不同?或者您忘了补偿分组单元格或附件项目的边距?我必须更多地了解您的UITableViewCell和布局更具体。

UITableViewCell grouped padding

一个单元格,其文字用于单元格textLabel.text,其高度由此代码计算:

#define FONT_SIZE 14.0f
#define CELL_CONTENT_MARGIN 10.0f  // label padding
#define CELL_MARGIN 10.0f  // cell margin for "grouped" style

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; {
    CGSize constraint = CGSizeMake(CGRectGetWidth(tableView.bounds) - (2 * CELL_MARGIN) - (CELL_CONTENT_MARGIN * 2), 20000.0f);
    CGSize size = [self.testString sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
    CGFloat height = MAX(size.height, 44.0f);
    return height + (CELL_CONTENT_MARGIN * 2);
}
相关问题