iOS 8中UITextView的sizeThatFits方法不能正确返回文本高度(自动布局)

9

我正在尝试使用从sizeThatFits得到的适当高度来垂直居中一个UITextView。有许多其他答案建议这是计算方式最恰当的方法。

(请注意,我已经尝试过纯文本和属性字符串,两者均表现出相同的行为)。

无论我尝试什么(甚至使用属性字符串并设置字体大小或行高),它总是只显示一定数量的文本字符(在这种情况下,是3行且总是完全一样的)。我错过了什么?

_textView.text = [_collectionDescription lowercaseString];
_textView.font = [UIFont fontLight:22];
_textView.textColor = [UIColor whiteColor];
_textView.textAlignment = NSTextAlignmentCenter;
_constraintTextViewHeight.constant = ceilf([_textView sizeThatFits:CGSizeMake(_textView.frame.size.width, FLT_MAX)].height);

[_textView setNeedsDisplay];
[_textView updateConstraints];

你有没有找到可行的答案?我一直在努力让sizeThatFits能够始终如一地工作,无论文本的大小如何。有时它会在底部留下额外的空间(不紧密),有时会有额外的空间,但缺少最后一行文本。有什么建议吗? - pizzafilms
请参见下面的答案 ;) - brandonscript
sizeThatFits:在iOS 8中已被弃用。 - fabb
7
不,sizeThatFits: 在 iOS 8 中的 UIView 并没有被弃用。链接 - Matthew Quiros
2个回答

16

与AutoLayout一如既往的,您需要执行:

[_textInfoView layoutIfNeeded];

(甚至根本不需要使用setNeedsDisplay)。

因此,完全可行:

_textView.text = [_collectionDescription lowercaseString];
_textView.font = [UIFont fontLight:22];
_textView.textColor = [UIColor whiteColor];
_textView.textAlignment = NSTextAlignmentCenter;
_constraintTextViewHeight.constant = ceilf([_textView sizeThatFits:CGSizeMake(_textView.frame.size.width, FLT_MAX)].height);

[_textView layoutIfNeeded];
[_textView updateConstraints];

1
当使用自动布局时,只需调用[_textView setNeedsUpdateConstraints],并通过更新约束来触发布局。当使用手动布局时,只需调用[_textView setNeedsLayout],无需调用layoutIfNeeded,因为它会自动完成。 - DawnSong

1

不要使用sizeThatFits:方法,可以尝试使用以下方法:

NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:14]};
// NSString class method: boundingRectWithSize:options:attributes:context is
// available only on ios7.0 sdk.
NSString *text = _textView.text;
CGRect rect = [text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                 options:NSStringDrawingUsesLineFragmentOrigin
                              attributes:attributes
                                 context:nil];
_constraintTextViewHeight.constant = CGRectGetHeight(rect)

该方法还考虑字符串text中的换行符。

3
NSDictionary *attributes = @{NSFontAttributeName: textView.font}; 这样会更好 :) - Alex Kosyakov
1
boundingRectWithSize也没有返回准确的数字。因此,我更倾向于避免使用该解决方案。 - Eugene Alexeev
1
我使用 sizeThatFits: 和 boundingRectWithSize: 得到了相同的结果,它们都返回了错误的结果。 - Corbin Miller

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接