【问题标题】:Wrapping UITextView with boundingRectWithSize:用 boundingRectWithSize 包装 UITextView:
【发布时间】: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


    【解决方案1】:

    我找到了答案。它在:

    textView.textContainer.lineFragmentPadding
    

    我需要从我的 textView 宽度中减去它。我猜除了 3 组插入和边距之外,还有另一个填充来源。

    【讨论】:

    • 实际上应该减去两次,因为两边都有填充。
    • JSQMessages 神奇的 2px 调整就是因为这个 lmao。它管理的其他 8px 来自每个 4px 的 sectionInset。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-22
    • 1970-01-01
    • 2014-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多