从UILabel获取截断的文本 [英] Get truncated text from UILabel
问题描述
无论如何我可以获得UILabel文本的截断版本吗?
Is there anyway I can get the truncated version of the text for a UILabel?
简而言之,我有一段文字和两个 UILabels
- 标签A,长2行,标签B,高度可变。标签A在标签B上方。想法是标签A显示文本段落的前两行,并且在某个用户操作时,标记B因为可见并显示文本的其余部分。
In short, I have a paragraph of text, and two UILabels
- label A, which is 2 lines long, and label B, which is a variable height. Label A is above label B. The idea is that label A shows the first two lines of the paragraph of text, and upon a certain user action, label B because visible and displays the rest of the text.
我无法确定标签B中的内容,因为我不知道标签A中显示的是什么。我还需要从标签A中删除... 。
I'm having trouble determining what should go in label B, as I don't know what's being shown in label A. I'd need to also remove the "..." from label A.
注意:我意识到这有点令人费解,但有一些很好的理由,我不会把这个问题弄得一团糟。
Note: I realize this is a bit convoluted but there are some good reasons for it, which I won't clutter up the question with.
推荐答案
我想知道你是否可以使用 NSString UIKit Additions ,以确定标签A的适合程度。
I wonder if you could use the methods in the NSString UIKit Additions to figure out how much fits into label A.
粗略的方法可能是从文本的第一个字符开始并测试它将占用的大小( -sizeWithFont:forWidth:lineBreakMod e:
也许?)然后继续添加一个字符,直到它不再适合你的标签A.
A crude way might be to start with the first character of your text and test for the size it would take up (-sizeWithFont:forWidth:lineBreakMode:
maybe?) and then keep adding characters one at a time until it doesn't fit into your label A any more.
I希望其他人可以提出更好的方法来做到这一点,但上述情况应该有效。
I hope somebody else can come up with a better way to do this, but the above should work.
更新
昨晚我看了一下我自己的应用程序的Core Text,并遇到了 CTFramesetterSuggestFrameSizeWithConstraints
。您可以使用此功能通过查看该函数中的 fitRange
来确定您的字符串中有多少符合标签。
Last night I looked a bit into Core Text for my own app and came across CTFramesetterSuggestFrameSizeWithConstraints
. You could maybe use this to figure out how much of your string fits into the label, by looking at the fitRange
in that function.
更新2:
我认为这应该可行,但我刚刚在这里输入了这个,所以它甚至可能都没有编译:
I think this should work, but I have just typed this in here, so it may not even compile:
UIFont *uiFont = [UIFont systemFontOfZise:13.0f]; // whichever font you're using
CTFontRef ctFont = CTFontCreateWithName((CFStringRef)uiFont.fontName, uiFont.pointSize, NULL);
NSDictionary *attr = [NSDictionary dictionaryWithObject:(id)ctFont forKey:(id)kCTFontAttributeName];
CFRelease(ctfont);
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:yourLabelText attributes:attr];
CTFrameSetterRef frameSetter = CTFrameSetterCreateWithAttributedString((CFAttributedStringRef)attrString);
[attrString release];
CFRange fitRange;
CTFrameSetterSuggestFrameSizeWithConstrains(
frameSetter,
CFRangeMake(0, 0),
NULL,
CGSizeMake(labelWidth, labelHeight),
&fitRange);
CFRelease(frameSetter);
CFIndex numberOfCharactersThatFit = fitRange.length;
这篇关于从UILabel获取截断的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!