Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

cocoa - NSButton setAlignment does not work

I used

[button setAlignment:NSCenterTextAlignment];

to make the text display at the center of the button.

It worked.

But if I set button title attribute before the code, button 'setAlignment' 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'.

}

title alignment always displayed as 'NSLeftTextAlignment' rather than 'NSCenterTextAlignment'.

Welcome any comment

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since you’re using an attributed string for the button title, the attributes in that string are responsible for setting the alignment.

To centre that attributed string, add an NSParagraphStyleAttributeName attribute with a centred 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 code above, I’ve created a single attrs dictionary holding all the attributes for the attributed string. From your code, it looks like the font colour should be applied to the whole string anyway.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...