目的
マウスカーソルが上に乗った時にハイライトする画像ボタンがほしい
方法
- インターフェースビルダで Squareの NSButtonを配置、Borderedのチェックを外す。
- NSButtonのカスタムクラスをMyHoverButtonにする
- NSButtonのアウトレットをコントローラに追加
MyHoverButtonの実装は以下の様な感じで
@interface MyHoverButton()
{
NSImage *image_normal;
NSImage *image_hover;
NSImage *image_alternate;
}
@end
@implementation MyHoverButton
- (void)awakeFromNib
{
[self createTrackingArea];
}
- (void)createTrackingArea
{
NSTrackingAreaOptions focusTrackingAreaOptions = NSTrackingActiveInActiveApp;
focusTrackingAreaOptions |= NSTrackingMouseEnteredAndExited;
focusTrackingAreaOptions |= NSTrackingAssumeInside;
focusTrackingAreaOptions |= NSTrackingInVisibleRect;
NSTrackingArea *focusTrackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect
options:focusTrackingAreaOptions
owner:self userInfo:nil];
[self addTrackingArea:focusTrackingArea];
}
-(void) setImageResources:(NSDictionary*) dict
{
NSString *normal = [dict objectForKey:@"normal"];
NSString *alternate = [dict objectForKey:@"alternate"];
NSString *hover = [dict objectForKey:@"hover"];
if (normal) {
image_normal = [NSImage imageNamed:normal];
self.bounds = NSMakeRect(0, 0, image_normal.size.width, image_normal.size.height);
}
if (alternate) {
image_alternate = [NSImage imageNamed:alternate];
}
if (hover) {
image_hover = [NSImage imageNamed:hover];
}
[self setImage:image_normal];
}
-(void)mouseEntered:(NSEvent *)theEvent
{
[self setImage:image_hover];
}
-(void)mouseExited:(NSEvent *)theEvent
{
[self setImage:image_normal];
}
-(void)mouseUp:(NSEvent *)theEvent
{
[self setImage:image_hover];
}
-(void)mouseDown:(NSEvent *)theEvent
{
[self setImage:image_alternate];
}
@end
コントローラ側でボタンのリソースを設定する
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"btn_normal", @"normal",
@"btn_alternate", @"alternate",
@"btn_hover" , @"hover", nil];
[_button setImageResources:dict];
}
画像リソースは一枚にまとめといたほうがいいとかトグルの対処はどうすんのとかいう話はあるけど直近の目的にはこれで十分。 createTrackingAreaを行わないとhoverの状態を検出できない。
参考 : http://stackoverflow.com/questions/7889419/cocoa-button-rollovers-with-mouseentered-and-mouseexited