根据iOS 7中的单元格文本计算单元格高度 [英] Calculate cell height based on cell's text in iOS 7
问题描述
有很多解决方案使用sizeWithFont或类似的东西,从iOS 7开始就被弃用。
There are many solutions out there that use "sizeWithFont" or something similar, which happens to be deprecated as of iOS 7.
这是我拼凑的一些代码到目前为止。高度改变,但完全没有准确:
Here is some code I have pieced together so far. The height changes, but not at all accurately:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
cell.textLabel.text = "The Cell's Text!";
cell.textLabel.numberOfLines = 0;
[cell.textLabel setLineBreakMode:NSLineBreakByWordWrapping];
[cell.textLabel sizeToFit];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
CGRect screenBounds = [[UIScreen mainScreen] bounds];
CGSize screenSize = screenBounds.size;
NSAttributedString *aString = [[NSAttributedString alloc] initWithString:"The Cell's Text!"];
UITextView *calculationView = [[UITextView alloc] init];
[calculationView setAttributedText:aString];
CGSize size = [calculationView sizeThatFits:CGSizeMake(screenSize.width, FLT_MAX)];
return size.height;
}
另一个例子,这里有一个类似的答案: https://stackoverflow.com/a/9828777/693121 虽然我之前说过,但这会使用已弃用的代码。
For another example, here's a similar answer: https://stackoverflow.com/a/9828777/693121 though as I said before, this utilizes deprecated code.
推荐答案
您应该使用文档中提到的方法来替换旧的 - boundingRectWithSize:options:attributes:context:。这是一个我认为应该工作的例子(无论如何它适用于多行标签)。
You should use the method that's mentioned in the docs to replace the old one -- boundingRectWithSize:options:attributes:context:. Here's an example that I think should work (it works with multi-line labels anyway).
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSStringDrawingContext *ctx = [NSStringDrawingContext new];
NSAttributedString *aString = [[NSAttributedString alloc] initWithString:@"The Cell's Text!"];
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];
return textRect.size.height;
}
这假设您希望文本视图的大小为self.view 。如果没有,您应该使用initWithFrame作为文本视图,并为boundingRectWithSize:参数传递calculateView.frame.size。
This assumes that you want the text view to be the size of self.view. If not, you should use initWithFrame for your text view, and pass calculationView.frame.size for the boundingRectWithSize: parameter.
这篇关于根据iOS 7中的单元格文本计算单元格高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!