如果正在包装的文本中有一个长字符串,sizeWithFont不会为UITextView提供正确的高度 [英] sizeWithFont doesn't give correct height for UITextView if there is a long string in the text being wrapped
问题描述
有没有办法使用以下方法获得正确的NSString大小:
Is there a way to get the correct size of an NSString using:
- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode
不会被2抛出或300个字符串。目前,如果我尝试在这些长字符串上使用此方法,则会错误地计算它们,并且最终会在UITextView的底部显示大量空格。
that doesnt get thrown off by 2 or 3 hundred character strings. At the moment if I try to use this method on these long strings it incorrectly calculates them and I end up with lots of whitespace at the bottom of the UITextView.
我'尝试使用UILineBreakModeWordWrap和UILineBreakModeCharacterWrap。
I've tried using UILineBreakModeWordWrap and UILineBreakModeCharacterWrap.
调整大小正在进行中
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGFloat result = 44.0f;
NSString* text = nil;
CGFloat width = 0;
CGFloat tableViewWidth;
CGRect bounds = [UIScreen mainScreen].bounds;
tableViewWidth = bounds.size.width;
width = tableViewWidth - 150;
text = stringWithLongWords;
if (text) {
CGSize textSize = { width, 20000.0f };
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:10.0f] constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap];
size.height += 50.0f;
result = MAX(size.height, 44.0f+30.0f);
}
return result;
}
推荐答案
UITextView
与包含在 UIScrollView
中的 UILabel
完全不同。它的行间距不同于字体大小和边距 sizeWithFont:constrainedToSize:linkBreakMode:
不占。
UITextView
is not exactly like a UILabel
wrapped in a UIScrollView
. It has line spacing different from the font size and margins that sizeWithFont:constrainedToSize:linkBreakMode:
doesn't account for.
了解字体大小,您可以计算行数并考虑行间距。您可以猜测边距并尝试欺骗 sizeWithFont:
以提供更有用的答案。
Knowing your font size you might be able to calculate the # of lines and take line spacing into account. You can guess at the margins and try to trick sizeWithFont:
to give a more useful answer.
流行的解决方案似乎是:
The popular solutions seem to be:
-
如果你不喜欢,只需使用
UILabel
如果您需要超链接$ c,则需要任何
UITextView
功能
just use a
UILabel
if you don't need anyUITextView
functionality
$ c>,覆盖 UIButtons
看起来像 UILabel上的超链接
if you need hyperlinks
, overlay UIButtons
that look like hyperlinks over a UILabel
使用屏幕外 UITextView
及其 sizeToFit
方法获得真实答案
use an off-screen UITextView
and its sizeToFit
method to get a real answer
我没有运气第三选项,但听起来应该有效,所以也许我做错了。
I had no luck w/ the 3rd option but it sounds like it should work, so perhaps I did something wrong.
我将尝试使用 UILabel
并覆盖超链接按钮。我们将看到结果如何。
I'm going to try using a UILabel
and overlaying buttons for hyperlinks. We'll see how that turns out.
如果失败,Loren Brichter(Tweetie成名)总会选择:将所有内容都绘制成 UIView
你自己使用 CoreGraphics
。
If that fails, there is always the option taken by Loren Brichter (of Tweetie fame): draw everything into a UIView
yourself using CoreGraphics
.
祝你好运!
这篇关于如果正在包装的文本中有一个长字符串,sizeWithFont不会为UITextView提供正确的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!