我用了
[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
包含属性字符串的所有属性的字典.从您的代码看,无论如何,字体颜色应该应用于整个字符串.
归档时间: |
|
查看次数: |
5187 次 |
最近记录: |