UITextView NSAttributedString大小 [英] UITextView NSAttributedString Size

查看:188
本文介绍了UITextView NSAttributedString大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个使用UITextView的应用程序.

I'm working on an app which uses a UITextView.

UITextView应该在垂直和水平方向上增长或缩小以适合其文本.为此,我在子类中重写了sizeToFit,并按如下方式设置了边界:

The UITextView should grow or shrink to fit its text, both vertically and horizontally. To do this, I'm overriding sizeToFit in a subclass, and I set the bounds like so:

- (void)sizeToFit {
    [self setBounds:(CGRect){.size = self.attributedText.size}];
}

问题在于,此大小只是不能反映字符串的正确大小,因为UITextView会剪切文本.我将边缘插值设置为零,所以这不应该成为问题吗?

The problem is that this size just doesn't reflect the correct size of the string, as the UITextView clips the text. I'm setting the edge insets to zero, so that shouldn't be an issue right?

在这一点上,我认为这是NSAttributedString的size属性的错误,但是如果我使用boundingRectWithSize:options:context:

At this point, I think it's a bug with NSAttributedString's size property, but the same thing happens if I use boundingRectWithSize:options:context:

[self setBounds:(CGRect){.size = [self.attributedText boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:0 context:nil].size}];

因此,也许无论什么代码在为NSAttributedString进行布局计算,都不能很好地与UITextView的布局计算配合使用.

So maybe whatever code is doing layout calculations for NSAttributedString doesn't play nicely with UITextView's layout calculations.

此处是演示该问题的示例项目.

欢迎任何想法!

我还应该指出,以下方法也不起作用:

- (void)sizeToFit {
    [self setBounds:(CGRect){.size = [self sizeThatFits:self.attributedText.size]}];
}

推荐答案

虽然不完美,但我最终使用了:

Though not perfect, I ended up using:

- (void)sizeToFit {

    CGSize textSize = self.attributedText.size;
    CGSize viewSize = CGSizeMake(textSize.width + self.firstCharacterOrigin.x * 2,
                                 textSize.height + self.firstCharacterOrigin.y * 2);

    [self setBounds:(CGRect){.size = [self sizeThatFits:viewSize]}];
}

- (CGPoint)firstCharacterOrigin {

    if (!self.text.length) return CGPointZero;

    UITextRange * range = [self textRangeFromPosition:[self positionFromPosition:self.beginningOfDocument offset:0]
                                           toPosition:[self positionFromPosition:self.beginningOfDocument offset:1]];
    return [self firstRectForRange:range].origin;
}

这篇关于UITextView NSAttributedString大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆