我有UITextView
根据其内容调整大小。但是iOS9给出了错误的高度值。我试过了UITextView height according to content is wrong in iOS 9。但这并不能解决我的问题。我的textview位于表格视图单元格内,我的单元格高度根据textview高度而变化。
newSize = [_cell.detailedTextView sizeThatFits:CGSizeMake(CGRectGetWidth(_cell.detailedTextView.bounds), CGRectGetHeight(_cell.detailedTextView.bounds))];
答案 0 :(得分:1)
请尝试这个。它可能对您有所帮助
+ (CGFloat)gettextViewHeight:(UITextView*)textView
{
CGSize constraint = CGSizeMake(textView.frame.size.width, 20000.0f);
CGSize size;
NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
CGSize boundingBox = [textView.text boundingRectWithSize:constraint
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:textView.font}
context:context].size;
size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));
return size.height;
}
答案 1 :(得分:0)
问题在于,boundingRect是针对大写字母高度而不是针对字体上升者而计算的。这将导致整个行不显示。
一旦确认,它就会正确显示:
func height(of string: String, in textView: UITextView) -> CGFloat
{
let font = textView.font ?? UIFont.preferredFont(forTextStyle: .headline)
let width = textView.bounds.size.width - 2.0 * textView.textContainer.lineFragmentPadding
let size = CGSize(width: width,
height: CGFloat.greatestFiniteMagnitude)
let height = string.boundingRect(with: size,
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: [NSAttributedString.Key.font: font],
context: nil).size.height
let insets = textView.textContainerInset.top + textView.textContainerInset.bottom
let diff = ceil(font.ascender - font.capHeight)
return height + insets + diff
}