是否可以在CATextLayer中使用自定义段落样式绘制字符串?

时间:2011-07-10 12:59:38

标签: cocoa macos core-animation catextlayer

我想画一个这样的列表:

 1. List item 1
 2. List item 2
 3. List item 3

这是我的代码:

NSTextList *list = [[NSTextList alloc] initWithMarkerFormat:@"{decimal}" options:0];
NSMutableParagraphStyle *paragraph = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[paragraph setTextLists:[NSArray arrayWithObject:list]];
[list release];
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:paragraph, NSParagraphStyleAttributeName, nil];
NSString *string = @"List item 1\nList item 2\nList item 3"
NSMutableAttributedString *attrString = [[[NSMutableAttributedString alloc] initWithString:string attributes:attributes] autorelease];
[paragraph release];

然后我将attrString设置为CATextLayer的字符串属性,但paragph样式不会应用于结果。

1 个答案:

答案 0 :(得分:1)

是的,这是可能的。您可以使用initWithHTML*initWithRTF*方法创建NSAttributedString 如果要以编程方式创建列表,可以将NSTextTab与NSTextList一起使用。但是你必须手动格式化字符串:

NSTextList *list = [[NSTextList alloc] initWithMarkerFormat:@"square" options:0];
NSMutableParagraphStyle *paragraph = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[paragraph setTextLists:[NSArray arrayWithObject:list]];
NSTextTab *t1 = [[NSTextTab alloc] initWithType:0 location:11.0f];
NSTextTab *t2 = [[NSTextTab alloc] initWithType:0 location:36.0f];
[paragraph setTabStops:[NSArray arrayWithObjects:t1, t2, nil]];
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:paragraph, NSParagraphStyleAttributeName, nil];
NSString *string = @"\t▪\tList item 1\n\t▪\tList item 2\n\t▪\tList item 3";
NSMutableAttributedString *attrString = [[[NSMutableAttributedString alloc] initWithString:string attributes:attributes] autorelease];
[paragraph release];
[list release];
[t1 release];
[t2 release];