我正在使用boundingRectWithSize:options:context:在iOS 7中尝试计算UITableViewCell中文本的动态高度。但是,使用此方法并NSStringDrawingUsesLineFragmentOrigin
作为选项,我总是在底部和顶部获得一些额外的空间。如果我切换到NSStringDrawingUsesDeviceMetrics
,那么单词就不会换行。这是截图:
对于包含更多文本的某些行,空间会更大。我该如何解决这个问题?我使用以下代码来获取包含文本的UILabel框架的大小:
- (CGSize)sizeWithMaxSize:(CGSize)constrainedSize andFontSize:(CGFloat)fontSize {
self.paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
self.paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
NSDictionary *dictionary = @{NSFontAttributeName: [UIFont systemFontOfSize:fontSize],
NSParagraphStyleAttributeName: self.paragraphStyle.copy,
NSForegroundColorAttributeName:[UIColor blackColor]};
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:self attributes:dictionary];
CGRect frame = [attributedString boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
return frame.size;
};
答案 0 :(得分:0)
如果你或这两个选项怎么办,因为它们只是位字段... NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesDeviceMetrics
所以而不是:
CGRect frame = [attributedString boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
你有:
CGRect frame = [attributedString boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesDeviceMetrics context:nil];