NSButton setAlignment does not work

后端 未结 1 426
你的背包
你的背包 2020-12-16 20:07

I used

[button setAlignment:NSCenterTextAlignment];

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

It worked.

But i

相关标签:
1条回答
  • 2020-12-16 20:41

    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.

    0 讨论(0)
提交回复
热议问题