我有一个面板 Nib ,其中一个文本字段有一个导出,该文本字段在 Nib 中设置为居中对齐。当我显示面板时,我希望该文本字段加粗。 由于 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];
现在文本字段再次居中,但粗体消失了。就好像属性字符串可以接受一个且仅一个属性设置。我错过了一些简单的事情吗?
最佳答案
您的代码中有一个拼写错误。 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];
关于cocoa - 可以为 NSTextField 设置对齐方式或字体,但不能同时设置两者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8029132/