如何从CTlineRef中提取文本字符串?

时间:2016-12-25 21:53:35

标签: ios objective-c cocoa-touch core-text ctlineref

如何从CTlineRef中提取文本字符串?

我知道我可以做CTLineGetStringRange(aLine),并且我有用于生成线的AttributedString(即:CFAttributedStringRef)。如何从AttributedString中提取文本字符串?

1 个答案:

答案 0 :(得分:4)

所以你有这个:

CFAttributedStringRef cfAttributedString = ...;
CTLineRef line = ...;
CFRange cfRange = CTLineGetStringRange(line);

CFRange转换为NSRange并将CFAttributedStringRef转换为NSAttributedString *

NSRange nsRange = NSMakeRange(cfRange.location, cfRange.length);
NSAttributedString *richText = (__bridge NSAttributedString *)cfAttributedString;

然后,您可以使用Objective-C消息来获取子字符串。如果你想要一个属性子字符串:

NSAttributedString *richSubtext = [richText attributedSubstringFromRange:nsRange];

如果你想要一个普通的子串:

NSString *substring = [richText.string substringWithRange:nsRange];

如果您因某些原因想要坚持使用Core Foundation功能(我不推荐它),您可以获得属性子字符串:

CFAttributedStringRef cfAttributedSubstring = CFAttributedStringCreateWithSubstring(
    NULL, cfAttributedString, cfRange);

或者像这样的普通子串:

CFStringRef cfString = CFAttributedStringGetString(cfAttributedString);
CFStringRef cfSubstring = CFStringCreateWithSubstring(NULL, cfString, cfRange);