OGeek|极客世界-中国程序员成长平台

标题: ios - 获取 UITextView 的实际高度 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 13:53
标题: ios - 获取 UITextView 的实际高度

我有一个 NSAttributedString 被传递到 UITextView:

NSAttributedString *str = @"A really long string ... that continues for awhile";

字符串的长度是随机的,我想将它传递给 UITextView。

myTextView.attributedText = str;

我需要 UITextView 的宽度为 300,但是如何找到高度?



Best Answer-推荐答案


如果我没记错的话,你可以这样做:

[myTextView sizeToFit];

然后从 myTextView.bounds.size.height 中检索高度。请注意,虽然 UITextViews 还会在边缘添加一些填充,因此您可能需要从高度中减去它。

如果我弄错了,这里有一个不太干净但可行的替代方案:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300.f, yourMaxHeight)];
label.attributedText = myTextView.attributedText;
label.numberOfLines = INFINITY;
[label sizeToFit];

CGFloat height = label.bounds.size.height;

这当然不包括 UITextView 填充。

关于ios - 获取 UITextView 的实际高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28075917/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4