可以为NSTextField设置对齐或字体,但不能同时设置两者

时间:2011-11-06 18:02:03

标签: cocoa nstextfield nsattributedstring

我有一个面板笔尖,其中一个文本字段的出口,在笔尖中设置为居中对齐。当我显示面板时,我希望这个文本字段是粗体。 由于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];

粗体显示OK,但现在该字段已左对齐。

我尝试添加setAlignment,但它没有效果:

[self.fooController.tfPanelCenteredField setAlignment:NSCenterTextAlignment];

所以我尝试将一个居中的parapraph样式添加到属性字符串的属性中:

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];

现在文本字段再次居中,但粗体消失了。就好像属性字符串可以接受一个并且只接受一个属性设置。我错过了一些简单的东西吗?

1 个答案:

答案 0 :(得分:8)

您的代码中有拼写错误。 NSFontNameAttribute应为NSFontAttributeName

所以你的属性字典是:

    NSFont *fontBolded = [NSFont fontWithName:@"Baskerville Bold" size:12.0f];
    NSMutableParagraphStyle *paragStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];   
    [paragStyle setAlignment:NSCenterTextAlignment]; 
    NSDictionary *dictBoldAttr = [NSDictionary dictionaryWithObjectsAndKeys:
                                  fontBolded, NSFontAttributeName,
                                  paragStyle, NSParagraphStyleAttributeName,
                                  nil];
相关问题