iPhone:将文本分成框架的行

标签 iphone core-text nsattributedstring

我有一个很长的文本和一个宽度为 300 且自动换行模式的 UILabel。我需要知道如果将我的文本设置为这个标签,将会有多少行......最主要的是获取世界“hello”所在的行。怎么做 ?如何将文本分成具有一定宽度的某些框架的行并获取该行的数组?谢谢....

最佳答案

好吧,要获取行数,您所要做的就是获取字符串并使用 sizeWithFont:constrainedToSize:,然后将高度除以标签的 UIFont 的 lineHeight 属性。

至于获取单独的行,我不确定是否有办法使用 Objective-C 来做到这一点,因此您可能必须使用 Core Text。

从字符串创建 NSAttributedString。

设置字体。

从 NSAttributedString 创建 CTFrameSetter

创建 CTFrame

使用 CTFrameGetLines 从 CTFrame 获取行的 CFArrayRef

枚举数组并找到您的单词。

如果您使用快速枚举,那么您将需要一个计数器来跟踪行号。

换行部分示例:

CTFontRef myFont = CTFontCreateWithName([font fontName], [font pointSize], NULL);
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:string];
[attStr addAttribute:(NSString *)kCTFontAttributeName value:(id)myFont range:NSMakeRange(0, attStr.length)];


CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attStr);

CGPathRef path = [[UIBezierPath bezierPathWithRect:textFrame] CGPathRef];
CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);

NSArray *lines = (NSArray *)CTFrameGetLines(frame);

您必须根据是否使用 ARC 添加适当的版本。

请注意,变量“font”是 UIFont。如果您想创建字体,则不必使用这些 fontName 和 pointSize 方法。

另请注意:这是 CTLineRef 对象的数组。使用CTLineGetStringRange获取整行的CFRange。然后使用它从 NSString 创建一个子字符串来进行搜索。

NSUInteger idx = 0;
for (CTLineRef line in lines) {
    CFRange lineRange = CTLineGetStringRange(line);
    NSRange range = NSMakeRange(lineRange.location, lineRange.length);

    NSString *lineString = [string substringWithRange:range];

    NSRange searchResultRange = [lineString rangeOfString:@"hello"];
    if (searchResultRange.location != NSNotFound) {
        // MATCH!
        break;
    }

    idx++;
 }

关于iPhone:将文本分成框架的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9827680/

相关文章:

iphone - 如何按字母顺序重新排列 NSArray 的元素(NSString)?

javascript - 在 UIWebView 中滚动

ios - locationForGlyphAtIndex 返回错误值

html - 如何从 iOS UILabel 对象中的 NSAttributedString(从 HTML 转换而来)中消除多余的换行符?

ios - NSAttributedString 中的颜色主题标签

iphone - 要求用户在 iPhone 崩溃后发送崩溃日志

iphone - 基本关键帧动画(旋转)

ios - Swift 中的 NSGlyph 到 CGGlyph(UInt32 到 UInt16)

ios - CoreText 和右对齐

ios - 计算字体大小以适合框架 - 核心文本 - NSAttributedString - iOS