3

テキストフィールドの1つに出口があるパネルペン先があります。これは、ペン先に中央揃えで設定されています。パネルを表示するときは、このテキストフィールドを太字にします。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];

そこで、属性付き文字列の属性に中央揃えのパラプラフスタイルを追加してみました。

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つだけの属性設定を受け入れることができるかのようです。私は何か簡単なものが欠けていますか?

4

1 に答える 1

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];
于 2011-11-06T18:09:56.707 に答える