场景:用于布局控件,根据界面的需要设置不同颜色的title。之前一直进入一个误区,直接自定义NSButton控件,其实这个方法是不好的,会使title重绘多次,复用性不高。
后来发现直接自定义NSButtonCell,可以只对title进行处理就可以了,而不必影响NSButton的其他属性。
下面是自定义NSButtonCell的方法。
MqjColorTitleButtonCell.h
#import <Cocoa/Cocoa.h>
@interface MqjColorTitleButtonCell : NSButtonCell
@end
MqjColorTitleButtonCell.m
<pre name="code" class="objc">#import "MqjColorTitleButtonCell.h"
@implementation MqjColorTitleButtonCell
- (NSRect)drawTitle:(NSAttributedString *)title withFrame:(NSRect)frame inView:(NSView *)controlView
{
NSSize titleSize = [title size];
//居中显示
CGFloat titleY = frame.origin.y + (frame.size.height - titleSize.height)/2;
NSRect rectTitle = frame;
rectTitle.origin.y = titleY;
NSMutableAttributedString *titleS