cocoa - NSButton setAlignment 不起作用

标签 cocoa

我用过

[button setAlignment:NSCenterTextAlignment];

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

成功了。

但是如果我在代码之前设置按钮标题属性,按钮“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'.

}

标题对齐方式始终显示为“NSLeftTextAlignment”而不是“NSCenterTextAlignment”。

欢迎大家留言

最佳答案

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

要使属性字符串居中,请添加具有居中对齐值的 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 字典,其中包含属性字符串的所有属性。从您的代码来看,字体颜色无论如何都应该应用于整个字符串。

关于cocoa - NSButton setAlignment 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7514157/

相关文章:

objective-c - 使用转换后的值对 NSTableColumn 进行排序

cocoa - 默认情况下,DispatchQueue 是.serial 还是.concurrent?

objective-c - NSBox 背景图片

objective-c - 我的声音去哪儿了?

objective-c - 通过扩展名注册新的 OS X 文件类型并与 Cocoa 应用程序关联

javascript - Cocoa:WKWebView/WebView 无法打开 Gmail 或 Inbox 内的链接

objective-c - Cocoa NSView 改变自动调整属性

xcode - IB_DESIGNABLE 类未在 Interface Builder 上呈现

xcode - 如何在 Xcode 4 中自动生成 Core Data GUI?

objective-c - 使用 cocoa C 桥作为命令行工具