我有UITableView
UITableViewCell
s,我以函数heightForRowAtIndexPath
设置每个单元格的高度:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
NSStringDrawingOptions opts = (NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading);
CGSize boundingRect = CGSizeMake(450.f, CGFLOAT_MAX);
CGSize size = [cell.detailTextLabel.text boundingRectWithSize:boundingRect
options:opts
attributes:[cell.detailTextLabel.attributedText attributesAtIndex:0 effectiveRange:nil]
context:nil].size;
CGFloat height = size.height;
size = [cell.textLabel.text boundingRectWithSize:boundingRect
options:opts
attributes:[cell.textLabel.attributedText attributesAtIndex:0 effectiveRange:nil]
context:nil].size;
height += size.height;
return height;
}
但是我获得的单元格对于文本而言太小,而较长的文本不适合:
在单元格中写入的文本按以下方式设置:
NSString *nickName = @"some nickname"; // gets the nickname
NSString title = [NSString stringWithFormat:@"%@ wrote:", nickName];
NSString *detail = @"some text"; // gets the content of the message
[cell.textLabel setText: title];
[cell.detailTextLabel setText: detail];
cell.detailTextLabel.numberOfLines = 0;
cell.detailTextLabel.lineBreakMode = NSLineBreakByWordWrapping;
为什么细胞的高度太短?
答案 0 :(得分:1)
从方法boundingRectWithSize:options:attributes:context:
https://developer.apple.com/reference/foundation/nsstring/1524729-boundingrectwithsize:
"此方法返回字符串中字形的实际边界"
缺少的是单元格的边距,可以使用cell.layoutMargins
访问:
height += cell.layoutMargins.top + cell.layoutMargins.bottom;
答案 1 :(得分:0)
尝试使用NSAttributedString
(Swift 3)
//change this value with the width of your UITableViewCell
let availableWidth:CGFloat = 355
let stringBoundingRect = NSAttributedString(string: "your string").boundingRect(with: CGSize(width: availableWidth, height: CGFloat.greatestFiniteMagnitude), options: [.usesDeviceMetrics, .usesLineFragmentOrigin], context: nil)
let height = stringBoundingRect.height
在Objective-C中:
// change this value with the width of your UITableViewCell
CGFloat availableWidth = 355;
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:@"your string"];
CGRect stringBoundingRect = [attrStr boundingRectWithSize:CGSizeMake(availableWidth, CGFLOAT_MAX) options: NSStringDrawingUsesLineFragmentOrigin| NSStringDrawingUsesDeviceMetrics context:nil];
CGFloat height = stringBoundingRect.size.height;