NSButton setAlignment不起作用

mon*_*bre 8 cocoa

我用了

[button setAlignment:NSCenterTextAlignment];
Run Code Online (Sandbox Code Playgroud)

使文本显示在按钮的中心.

有效.

但是如果我在代码之前设置按钮标题属性,按钮'setAlignment'将不起作用

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

}
Run Code Online (Sandbox Code Playgroud)

标题对齐始终显示为"NSLeftTextAlignment"而不是"NSCenterTextAlignment".

欢迎任何评论

小智 20

由于您使用按钮标题的属性字符串,因此该字符串中的属性负责设置对齐.

要将该属性字符串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];
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我创建了一个attrs包含属性字符串的所有属性的字典.从您的代码看,无论如何,字体颜色应该应用于整个字符串.

  • 答案当然是正确的.我只是想表达我对在mac上开发ui的方式设计方式的沮丧......我的意思是......有一个按钮带有自定义颜色居中的文本...这很吓人荒谬.醒来苹果! (3认同)