我有一个面板笔尖,它的一个文本字段有一个出口,它在笔尖中设置为居中对齐。当我显示面板时,我希望这个文本字段加粗。由于 NSTextField 是 NSControl 的子类,它可以使用 setAttributedStringValue 方法并获取属性字符串。所以我加入了这样的粗体字体:
NSFont *fontBolded = [NSFont fontWithName:@"Baskerville Bold" size:12.0f];
NSDictionary *dictBoldAttr = [NSDictionary dictionaryWithObject:fontBolded forKey:NSFontAttributeName];
NSString *sHelloUser = NSLocalizedString(@"Hello User", @"Hello User");
NSAttributedString *attrsHelloUser = [[NSAttributedString alloc] initWithString: sHelloUser attributes:dictBoldAttr];
[self.fooController.tfPanelCenteredField setAttributedStringValue:attrsHelloUser];
[attrsHelloUser release];
粗体显示正常,但该字段现在左对齐。
我尝试添加一个 setAlignment,但它没有效果:
[self.fooController.tfPanelCenteredField setAlignment:NSCenterTextAlignment];
所以我尝试在属性字符串的属性中添加一个居中的段落样式:
NSFont *fontBolded = [NSFont fontWithName:@"Baskerville Bold" size:12.0f];
NSMutableParagraphStyle *paragStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[paragStyle setAlignment:NSCenterTextAlignment];
NSDictionary *dictBoldAttr = [NSDictionary dictionaryWithObjectsAndKeys:paragStyle, NSParagraphStyleAttributeName, fontBolded, NSFontNameAttribute, nil];
NSString *sHelloUser = NSLocalizedString(@"Hello User", @"Hello User");
NSAttributedString *attrsHelloUser = [[NSAttributedString alloc] initWithString: sHelloUser attributes:dictBoldAttr];
[self.fooController.tfPanelCenteredField setAttributedStringValue:attrsHelloUser];
[attrsHelloUser release];
[paragStyle release];
现在文本字段再次居中,但粗体消失了。就好像属性字符串可以接受一个且只有一个属性设置。我错过了一些简单的东西吗?