2011-09-22 5 views
7

NSButtonのsetAlignmentが機能しない

[button setAlignment:NSCenterTextAlignment]; 

を使って、ボタンの中央にテキストを表示させました。

それは働いた。

しかし、コードの前にボタンのタイトル属性を設定した場合、 'setAlignment'ボタンは機能しません。 'NSCenterTextAlignment'ではなく 'NSLeftTextAlignment'として常に表示されます。

任意のコメントをようこそ

+0

タイトルが帰属されていない場合は動作しますか?たぶん、アトリビュートされた文字列のアライメントを設定する必要があります。 –

+0

タイトルが帰属されていない場合は機能しましたが、アトリビュートされた文字列にアラインメントを追加する方法がわかりません – monsabre

+0

質問を編集しました – monsabre

答えて

18

を歓迎、その文字列の属性は、アライメントを設定するための責任があります。

文字列を起因中央に、中央揃え値でNSParagraphStyleAttributeName属性を追加します。

NSMutableParagraphStyle *centredStyle = [[[NSParagraphStyle defaultParagraphStyle] mutableCopy] autorelease]; 
[centredStyle setAlignment:NSCenterTextAlignment]; 

NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:centredStyle, 
         NSParagraphStyleAttributeName, 
         [NSFont fontWithName:fontName size:fontSize], 
         NSFontAttributeName, 
         fontColor, 
         NSForegroundColorAttributeName, 
         nil]; 
NSMutableAttributedString *attributedString = 
[[NSMutableAttributedString alloc] initWithString:[button title] 
           attributes:attrs]; 

[button setAttributedTitle: attributedString]; 

を上記のコードでは、私は属性付き文字列のすべての属性を保持する単一attrs辞書を作成しました。あなたのコードからは、フォントの色が文字列全体に適用されるように見えます。

+3

答えはもちろん正しいです。私は、物事がMacでのUIの開発の観点から設計されている方法への私の不満を表現したいと思います...私は...カスタムカラーのテキストを中心としたボタンを持っているので、ばかげたアップルアップ! –

+0

@RaduSimionescuココアの世界へようこそ –