【发布时间】:2015-11-11 13:18:43
【问题描述】:
我正在尝试使用以下代码动态更新 UITextView 的高度,但结果始终偏离几个像素,这导致文本视图换行但大小不合适。一旦输入另一个(或两个)字符,显示就会相应更新。
我查看了各种帖子(许多帖子已过时,因为它们引用了已弃用的 sizeThatFits),但我没有发现任何不同之处。那些使用 boundingRectWithSize 的:(NSString 或 NSAttributedString——我都试过了)看起来像下面这样:
CGRect boundingRect = [string boundingRectWithSize: CGSizeMake(CGRectGetWidth(textView.frame), CGFLOAT_MAX)
options: NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes: @{
NSFontAttributeName : textView.font
}
context: NULL];
float h = ceil(CGRectGetHeight(boundingRect));
textViewHeightLayoutConstraint.constant = h;
我知道你要说的第一件事是:插图。这是我的设置代码:
textView.textContainerInset = UIEdgeInsetsZero;
textView.contentInset = UIEdgeInsetsZero;
textView.layoutMargins = UIEdgeInsetsZero;
还有其他 insets 设置吗?
旁注:我使用 MuseoSans 作为字体。
破解解决方案
我已经通过检查宽度是否在阈值内(目前测试后为 9px)“修复”了该问题,如果是,则假装像这样添加了额外的行:
float fontHeight = ceil([@"lp" sizeWithAttributes: @{
NSFontAttributeName : textView.font
}].height);
if ((CGRectGetWidth(textView.frame) - ceil(CGRectGetWidth(boundingRect))) <= 9.f)
h += fontHeight;
上面允许我捕获最大可能的高度,然后在我的文本视图上强制它的高度。文本视图会正确换行并在下一行显示文本。
想法?
小更新
添加这个没有效果:
NSMutableParagraphStyle *paragraphStyle = [NSParagraphStyle.defaultParagraphStyle mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
CGRect boundingRect = [string boundingRectWithSize: CGSizeMake(CGRectGetWidth(textView.frame), CGFLOAT_MAX)
options: NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes: @{
NSFontAttributeName : textView.font,
NSParagraphStyleAttributeName : paragraphStyle
}
context: NULL];
【问题讨论】:
标签: ios autolayout uitextview