在Mac OSX的软件中经常会使用到NSSearchFiled这个控件,用它来做搜索框还是非常方便的,之前使用它时都是采用的默认造型,但最近的一个项目因为整体风格的原因,它的外观显然不满足使用,最初本打算自己去实现一个类似的NSSearchField,但发现要实现功能和NSSearchField一样的控件,需要的代码量还不少,于是最终还是选择了去派生一个风格不一样的NSSearchFieldCell,简单几行代码便可实现修改背景色、光标颜色、放大镜图标和退出图标,恰好这两天有人写邮件问我如何修改NSSearchField的样式,我就随便贴出这几行代码,其实非常简单:
#import "THSearchFieldCell.h"
@implementation THSearchFieldCell
//通过代码实例化
- (id)init
{
self = [super init];
if (self)
{
[self setUp];
}
return self;
}
//通过xib实例化
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
[self setUp];
}
return self;
}
- (void)setUp
{
//重写搜索图标
NSButtonCell *searchButtonCell = [self searchButtonCell];
NSImage *searchImage = [NSImage imageNamed:NSImageNameHomeTemplate];
[searchImage setSize:NSMakeSize(16, 16)];
[searchButtonCell setImage:searchImage];
[searchButtonCell setAlternateImage:searchImage];
//重写取消图标
NSButtonCell *cancelButtonCell = [self cancelButtonCell];
NSImage *cancelImage = [NSImage imageNamed:NSImageNameRevealFreestandingTemplate];
[cancelImage setSize:NSMakeSize(16, 16)];
[cancelButtonCell setImage:cancelImage];
[cancelButtonCell setAlternateImage:cancelImage];
}
//重写该方法实现对背景色的修改
- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
NSRect rect = controlView.bounds;
NSBezierPath *bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect
xRadius:NSHeight(rect)/2
yRadius:NSHeight(rect)/2];
[[NSColor orangeColor] set];
[bezierPath fill];
[super drawInteriorWithFrame:cellFrame inView:controlView];
}
//重写该方法实现对光标颜色的修改
- (NSText *)setUpFieldEditorAttributes:(NSText *)textObj
{
NSText *text = [super setUpFieldEditorAttributes:textObj];
[(NSTextView*)text setInsertionPointColor:[NSColor whiteColor]];
return text;
}
@end
完整的测试代码下载:THSearchFieldDemo.zip