NSButton不能像UIButton那樣簡單的修改title的顏色,或者說NSButton不能像UIButton那樣做很多事,使用起來真的很不方便。
經(jīng)過大量研究測試,終于發(fā)現(xiàn)一種修改文字顏色的相對來說比較簡單的方式-用NSAttributedString;不說了,代碼如下:
// 創(chuàng)建段落樣式,主要是為了設(shè)置居中
NSMutableParagraphStyle *pghStyle = [[NSMutableParagraphStyle alloc] init];
pghStyle.alignment = NSTextAlignmentCenter;
// 創(chuàng)建Attributes,設(shè)置顏色和段落樣式
NSDictionary *dicAtt = @{NSForegroundColorAttributeName: [NSColor whiteColor], NSParagraphStyleAttributeName: pghStyle};
// 創(chuàng)建NSAttributedString賦值給NSButton的attributedTitle屬性
btn.attributedTitle = [[NSAttributedString alloc] initWithString:@"解綁" attributes:dicAtt];
4行代碼即可,比起一來就說什么重寫drawRect的簡單多了!
但是,經(jīng)過實際操作發(fā)現(xiàn)該方法會導(dǎo)致內(nèi)存泄漏,實在不知是什么原因?qū)е碌?,私下猜測是Apple的bug吧。但是也不是沒有解決方法,經(jīng)過大量測試,發(fā)現(xiàn)以下方法可以解決內(nèi)存泄漏的問題。
// 創(chuàng)建段落樣式,主要是為了設(shè)置居中
NSMutableParagraphStyle *pghStyle = [[NSMutableParagraphStyle alloc] init];
pghStyle.alignment = NSTextAlignmentCenter;
// 創(chuàng)建Attributes,設(shè)置顏色和段落樣式
NSDictionary *dicAtt = @{NSForegroundColorAttributeName: [NSColor whiteColor], NSParagraphStyleAttributeName: pghStyle};
// 創(chuàng)建NSAttributedString賦值給NSButton的attributedTitle屬性;必需從NSButton.attributedTitle創(chuàng)建,否則會有內(nèi)存泄漏;
// 給NSButton先賦值一個字符串,為的是后面替換,如果NSButton的title是空字符串的話,也會內(nèi)存泄漏
btn.title = @" "; // 這里的字符串有一個空格
// 用NSButton.attributedTitle屬性創(chuàng)建一個NSMutableAttributedString對象
NSMutableAttributedString *attTitle = [[NSMutableAttributedString alloc] initWithAttributedString:btn.attributedTitle];
// 替換文字
[attTitle replaceCharactersInRange:NSMakeRange(0, 1) withString:@"解綁"];
// 添加屬性
[attTitle addAttributes:dicAtt range:NSMakeRange(0, 2)];
// 賦值給NSButton.attributedTitle屬性,不會再有內(nèi)存泄漏
btn.attributedTitle = attTitle;
經(jīng)過大量測試,發(fā)現(xiàn)只有這種方法不會內(nèi)存泄漏,我也是醉了。