我正在使用一个使用UITextView的应用程序.
UITextView应该增大或缩小以适合其文本,包括垂直和水平.为此,我在子类中重写sizeToFit,并设置边界如下:
- - (void)sizeToFit {
- [self setBounds:(CGRect){.size = self.attributedText.size}];
- }
问题是这个大小只是没有反映字符串的正确大小,因为UITextView会剪切文本.我将边缘插入设置为零,所以这不应该是一个问题吧?
在这一点上,我认为这是NSAttributedString的size属性的一个错误,但是如果我使用boundingRectWithSize,则会发生同样的事情:options:context:
- [self setBounds:(CGRect){.size = [self.attributedText boundingRectWithSize:CGSizeMake(CGFLOAT_MAX,CGFLOAT_MAX) options:0 context:nil].size}];
因此,无论代码是什么,NSAttributedString的布局计算都无法与UITextView的布局计算很好地协作.
Here is example project which demonstrates the issue.
欢迎任何想法!
编辑:我还应该指出以下不起作用:
- - (void)sizeToFit {
- [self setBounds:(CGRect){.size = [self sizeThatFits:self.attributedText.size]}];
- }
解决方法
虽然不完美,但我最终使用:
- - (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;
- }