改变NSButton字(title)的颜色

分手后的思念是犯贱 2022-06-18 04:15 380阅读 0赞

转自我的简书:http://www.jianshu.com/p/a9e86b79a2d4

#


NSButton不能像UIButton那样简单的修改title的颜色,或者说NSButton不能像UIButton那样做很多事,使用起来真的很不方便。
经过大量研究测试,终于发现一种修改文字颜色的相对来说比较简单的方式-用NSAttributedString;不说了,代码如下:

  1. // 创建段落样式,主要是为了设置居中
  2. NSMutableParagraphStyle pghStyle = [[NSMutableParagraphStyle alloc] init];
  3. pghStyle.alignment = NSTextAlignmentCenter;
  4. // 创建Attributes,设置颜色和段落样式
  5. NSDictionary dicAtt = @{NSForegroundColorAttributeName: [NSColor whiteColor], NSParagraphStyleAttributeName: pghStyle};
  6. // 创建NSAttributedString赋值给NSButton的attributedTitle属性
  7. btn.attributedTitle = [[NSAttributedString alloc] initWithString:@"解绑" attributes:dicAtt];

4行代码即可,比起一来就说什么重写drawRect的简单多了!

但是,经过实际操作发现该方法会导致内存泄漏,实在不知是什么原因导致的,私下猜测是Apple的bug吧。但是也不是没有解决方法,经过大量测试,发现以下方法可以解决内存泄漏的问题。

  1. // 创建段落样式,主要是为了设置居中
  2. NSMutableParagraphStyle *pghStyle = [[NSMutableParagraphStyle alloc] init];
  3. pghStyle.alignment = NSTextAlignmentCenter;
  4. // 创建Attributes,设置颜色和段落样式
  5. NSDictionary *dicAtt = @{NSForegroundColorAttributeName: [NSColor whiteColor], NSParagraphStyleAttributeName: pghStyle};
  6. // 创建NSAttributedString赋值给NSButton的attributedTitle属性;必需从NSButton.attributedTitle创建,否则会有内存泄漏;
  7. // 给NSButton先赋值一个字符串,为的是后面替换,如果NSButton的title是空字符串的话,也会内存泄漏
  8. btn.title = @" "; // 这里的字符串有一个空格
  9. // 用NSButton.attributedTitle属性创建一个NSMutableAttributedString对象
  10. NSMutableAttributedString *attTitle = [[NSMutableAttributedString alloc] initWithAttributedString:btn.attributedTitle];
  11. // 替换文字
  12. [attTitle replaceCharactersInRange:NSMakeRange(0, 1) withString:@"解绑"];
  13. // 添加属性
  14. [attTitle addAttributes:dicAtt range:NSMakeRange(0, 2)];
  15. // 赋值给NSButton.attributedTitle属性,不会再有内存泄漏
  16. btn.attributedTitle = attTitle;

经过大量测试,发现只有这种方法不会内存泄漏,我也是醉了。

发表评论

表情:
评论列表 (有 0 条评论,380人围观)

还没有评论,来说两句吧...

相关阅读

    相关 echo改变输出颜色

    这篇并不是严格意义上的原创,只是整合了网上其他人的资料,加上自己的理解。 echo命令介绍 功能说明:显示文字。 语   法:echo \[-ne\]\[字符串\]