Cocoa NSButton设置对齐不起作用
我曾经 使文本显示在按钮的中心 成功了 但是,如果我在代码之前设置按钮标题属性,按钮“setAlignment”将不起作用Cocoa NSButton设置对齐不起作用,cocoa,Cocoa,我曾经 使文本显示在按钮的中心 成功了 但是,如果我在代码之前设置按钮标题属性,按钮“setAlignment”将不起作用 [button setAlignment:NSCenterTextAlignment]; 标题对齐方式始终显示为“NSLeftTextAlignment”而不是“nsCenter TextAlignment” 欢迎任何评论因为您正在为按钮标题使用属性字符串,所以该字符串中的属性负责设置对齐方式 若要使该属性化字符串居中,请添加具有居中对齐值的NSParagraphStyl
[button setAlignment:NSCenterTextAlignment];
标题对齐方式始终显示为“NSLeftTextAlignment”而不是“nsCenter TextAlignment”
欢迎任何评论因为您正在为按钮标题使用属性字符串,所以该字符串中的属性负责设置对齐方式 若要使该属性化字符串居中,请添加具有居中对齐值的NSParagraphStyleAttributeName属性:
- (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'.
}
在上面的代码中,我创建了一个ATTR字典,其中包含属性字符串的所有属性。从您的代码来看,字体颜色似乎应该应用于整个字符串。如果标题没有属性,它是否有效?也许你需要在属性字符串中设置对齐方式。如果标题没有属性,它会起作用,但我不知道如何将对齐方式添加到属性字符串中答案当然是正确的。我只是想表达我对mac上ui开发的设计方式的失望。。。我是说。。。有这么多的代码有一个自定义的颜色为中心的文本按钮。。。这太荒谬了。醒醒苹果!!!
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];