NSButton setAlignment not working

I used

[button setAlignment:NSCenterTextAlignment]; 

so that the text appears in the center of the button.

It worked.

But if I set the button title attribute before the code, the 'setAlignment' button will not work

 - (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'. } 

header alignment is always displayed as "NSLeftTextAlignment" and not "NSCenterTextAlignment".

Welcome any comment

+7
source share
1 answer

Since you use the attribute string for the button name, the attributes in this string are responsible for adjusting the alignment.

To center this attribute string, add the NSParagraphStyleAttributeName attribute with a centered alignment value:

 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]; 

In the above code, Ive created a single attrs dictionary containing all the attributes of an attribute string. From your code, it seems the font color should apply to the whole line.

+18
source

All Articles