gre*_*reg 5 uitextview ios autolayout
我正在尝试使用以下代码动态更新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;
Run Code Online (Sandbox Code Playgroud)
我知道你要说的第一件事是:内插.这是我的设置代码:
textView.textContainerInset = UIEdgeInsetsZero;
textView.contentInset = UIEdgeInsetsZero;
textView.layoutMargins = UIEdgeInsetsZero;
Run Code Online (Sandbox Code Playgroud)
还有其他插图设置吗?
旁注:我正在使用MuseoSans作为字体.
黑客解决方案
我通过检查宽度是否在一个阈值(当前是测试的9px)之内"修复"了这个问题,如果是,假装添加了一条额外的行,如下所示:
float fontHeight = ceil([@"lp" sizeWithAttributes: @{
NSFontAttributeName : textView.font
}].height);
if ((CGRectGetWidth(textView.frame) - ceil(CGRectGetWidth(boundingRect))) <= 9.f)
h += fontHeight;
Run Code Online (Sandbox Code Playgroud)
上面允许我捕捉最大可能的高度,然后在我的文本视图上强制它的高度.文本视图确实适当地换行并在下一行显示文本.
想法?
小更新
添加此项无效:
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];
Run Code Online (Sandbox Code Playgroud)
我找到了答案.在里面:
textView.textContainer.lineFragmentPadding
Run Code Online (Sandbox Code Playgroud)
我需要从textView宽度中减去它.我想除了3组插图和边距之外还有另一个填充源.