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

标签 cocoa nstextfield nsattributedstring

我有一个面板 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/

相关文章:

objective-c - NSTextField + NSTimer

cocoa - 我需要对 NSTextFieldCell 进行一些高级文本样式设置

cocoa - 使 NSWindow.isMovableByWindowBackground 与 NSTextField 一起使用

ios - 将文本永久附加到 UITextView

ios - 如何在没有占位符文本的情况下设置属性文本?

ios - Swift iOS - 如何实现多行不同字号的SegmentedControl

objective-c - 有时我想阻止我的 Cocoa 应用程序启动,如何在 init 中阻止它?

iphone - 从 AFImageRequestOperation 中的成功 block 返回图像

iphone - 你能用 NSPredicate 指定 "select unique name from ..."吗?

objective-c - 创建具有订单支持的 NSDictionary