我正在创建一个 iOS 应用程序,我想显示一个属性字符串,其中包含在 UITextView 中指定的特定制表位。我还想使用 drawRect 中的核心文本将它们直接绘制到 UIViews 中。我希望(如果可能)在两种情况下都使用相同的属性字符串。
因此,在我的应用程序中,我创建了一个 CFAttributedStringRef 或 NSAttributedString 并将 CTParagraphStyle 属性应用到它。然后,我尝试在 UITextView 中显示属性字符串,但出现如下崩溃:
-[__NSCFType headIndent]: unrecognized selector sent to instance 0x7545080
po 0x7545080
$0 = 122966144 CTParagraphStyle:
base writing direction = -1, alignment = 4, line break mode = 0,
default tab interval = 0
first line head indent = 0, head indent = 0, tail indent = 0
line height multiple = 0, maximum line height = 0, minimum line height = 0
line spacing adjustment = 0, paragraph spacing = 0,
paragraph spacing before = 0
tabs:
(
"CTTextTab: location = 20, alignment = 0, options = (none)\n",
"CTTextTab: location = 40, alignment = 0, options = (none)\n",
"CTTextTab: location = 60, alignment = 0, options = (none)\n",
"CTTextTab: location = 80, alignment = 0, options = (none)\n",
"CTTextTab: location = 100, alignment = 0, options = (none)\n",
"CTTextTab: location = 120, alignment = 0, options = (none)\n"
)
我明白发生了什么,但我想知道我是否有其他方法可以做我想做的事情。iOS 上的 NSMutableParagraphStyle 不支持制表位,但我注意到 OS X 上的 NSMutableParagraphStyle 确实具有此功能。这让我认为 iOS NSMutableParagraphStyle 有一天可能会支持这一点。
同时,有没有办法将制表位添加到 CFAttributedStringRef 或 NSAttributedString 并且仍然有 UITextView 显示它?
有问题的来源是:
- (void)viewWillAppear:(BOOL)animated
{
CFDictionaryRef attrs = (__bridge CFDictionaryRef) @{};
CFAttributedStringRef a = CFAttributedStringCreate(
kCFAllocatorDefault, CFSTR("a\tb\tc\td"), attrs);
CFMutableAttributedStringRef attrStr;
attrStr = CFAttributedStringCreateMutableCopy(
kCFAllocatorDefault, CFAttributedStringGetLength(a), a);
CFArrayRef tabStops = (__bridge CFArrayRef) @[
(__bridge id) CTTextTabCreate(0, 20, NULL),
(__bridge id) CTTextTabCreate(0, 40, NULL),
(__bridge id) CTTextTabCreate(0, 60, NULL),
(__bridge id) CTTextTabCreate(0, 80, NULL),
(__bridge id) CTTextTabCreate(0, 100, NULL),
(__bridge id) CTTextTabCreate(0, 120, NULL)];
const CTParagraphStyleSetting paraSettings[] = {
{kCTParagraphStyleSpecifierTabStops, sizeof(CFArrayRef), &tabStops},
};
CTParagraphStyleRef paraStyle = CTParagraphStyleCreate(
paraSettings,
sizeof(paraSettings) / sizeof(CTParagraphStyleSetting));
CFRange range = CFRangeMake(0, CFAttributedStringGetLength(attrStr));
CFAttributedStringSetAttribute(
attrStr, range, kCTParagraphStyleAttributeName, paraStyle);
CFRelease(paraStyle);
CFIndex i, count = CFArrayGetCount(tabStops);
for (i = 0; i < count; i++) {
CFRelease(CFArrayGetValueAtIndex(tabStops, i));
}
[[self textView] setAttributedText:
(__bridge NSAttributedString *)(attrStr)];
}