2011-09-22 74 views
7

我用NSButton參考setAlignment不起作用

[button setAlignment:NSCenterTextAlignment]; 

,使文本顯示在按鈕的中心。

它工作。

但是,如果我的代碼,按鈕「參考setAlignment」之前設置按鈕title屬性將無法正常工作

- (void)setButtonTitle:(NSButton*)button fontName:(NSString*)fontName fontSize:(CGFloat)fontSize fontColor:(NSColor*)fontColor; 
{ 

    NSMutableAttributedString *attributedString = 
    [[NSMutableAttributedString alloc] initWithString:[button title] 
            attributes:[NSDictionary dictionaryWithObject:[NSFont fontWithName:fontName size:fontSize] 
                      forKey:NSFontAttributeName]]; 
    [attributedString addAttribute:NSForegroundColorAttributeName 
           value:fontColor 
           range:NSMakeRange(0, [[button title] length])]; 


    [button setAttributedTitle: attributedString]; 
    [button setAlignment:NSCenterTextAlignment];//button title alignment always displayed as 'NSLeftTextAlignment' rather than 'NSCenterTextAlignment'. 

} 

標題對齊始終顯示爲「NSLeftTextAlignment」而不是「NSCenterTextAlignment」。

歡迎任何評論

+0

如果標題沒有歸因,它會起作用嗎?也許你需要在屬性字符串中設置對齊方式。 – 2011-09-22 11:46:28

+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歡迎來到可可世界 –