附加NSAttributedStrings无法按预期工作

时间:2013-06-03 19:28:22

标签: macos nsattributedstring catextlayer

我正在尝试将属性字符串附加到“G#m7”这样的和弦名称,其中#和7是上标。我是这样做的:

NSFont* font = [NSFont fontWithName:kGillSans size:24];
NSMutableDictionary* attributeNormal = [[NSMutableDictionary alloc] init];
[attributeNormal setObject:font forKey:NSFontAttributeName];
[attributeNormal setObject:color forKey:NSForegroundColorAttributeName];

NSFont* fontSmall = [NSFont fontWithName:kGillSans size:14];
NSMutableDictionary* attributeSuperScript = [[NSMutableDictionary alloc] init];
[attributeSuperScript setObject:fontSmall forKey:NSFontAttributeName];
[attributeSuperScript setObject:[NSNumber numberWithInteger:5] forKey:NSSuperscriptAttributeName];
[attributeSuperScript setObject:color forKey:NSForegroundColorAttributeName];


NSAttributedString* pitch = [[NSAttributedString alloc] initWithString:@"G" attributes:attributeNormal];

NSAttributedString* accidental = [[NSAttributedString alloc] initWithString:@"#" attributes:attributeSuperScript];

NSAttributedString* quality = [[NSAttributedString alloc] initWithString:@"m" attributes:attributeNormal];

NSAttributedString* seventh = [[NSAttributedString alloc] initWithString:@"7" attributes:attributeSuperScript];

NSMutableAttributedString* fullString = [[NSMutableAttributedString alloc] initWithAttributedString:pitch];
[fullString appendAttributedString:accidental];
[fullString appendAttributedString:quality];
[fullString appendAttributedString:seventh];

然后我将它添加到CATextLayer进行显示。不幸的是,它没有按预期工作。上标不是上标,并且随之返回的[fullstring size]是关闭的,导致难以放置图层。我打开边框宽度以演示尺寸问题。

enter image description here

我已经尝试了上标属性的不同字体大小和值。有任何想法吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

NSFont* font = [NSFont fontWithName:@"GillSans" size:24];
NSDictionary * attributeNormal = @{NSFontAttributeName: font,
                                   NSForegroundColorAttributeName: [NSColor blackColor]};

NSFont* fontSmall = [NSFont fontWithName:@"GillSans" size:14];
NSDictionary * attributeSuperScript = @{NSFontAttributeName: fontSmall,
                                        NSSuperscriptAttributeName: @(2),
                                        NSForegroundColorAttributeName: [NSColor blackColor]};

NSMutableAttributedString* fullString =
[[NSMutableAttributedString alloc]
 initWithAttributedString:[[NSAttributedString alloc]
                           initWithString:@"G"
                           attributes:attributeNormal]];

[fullString appendAttributedString:
 [[NSAttributedString alloc] initWithString:@"#"
                                 attributes:attributeSuperScript]];

[fullString appendAttributedString:
 [[NSAttributedString alloc] initWithString:@"m"
                                 attributes:attributeNormal]];

[fullString appendAttributedString:
 [[NSAttributedString alloc] initWithString:@"7"
                                 attributes:attributeSuperScript]];