Checking if NSButton is down on drawRect

2019-06-18 16:09发布

I would like to check if my custom NSButton is currently in a pressed state (the user is clicking down on it) in my custom drawRect method. Something like this:

- (void)drawRect:(NSRect)dirtyRect{
    if ([self buttonIsInPressedState]) {
        [[self alternateBGImage] drawInRect:dirtyRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0f];
    }else{
        [[self BGImage] drawInRect:dirtyRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0f];
    }
    [super drawRect:dirtyRect];
}

How would you check a thing like that? Is it possible?

SOLUTION

I ended up checking the mouseDownFlags on the buttons cell. Don't know if it's the "right" way to do it, so let me know if you have a better suggestion:

- (void)drawRect:(NSRect)dirtyRect{        
    if ([self.cell mouseDownFlags] == 0) {
        [[self BGImage] drawInRect:dirtyRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0f];
    }else{
        [[self alternateBGImage] drawInRect:dirtyRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0f];
    }

    [super drawRect:dirtyRect];
}

4条回答
不美不萌又怎样
2楼-- · 2019-06-18 16:53

I don't think "drawRect:" is the right place to try to catch this.

You can subclass NSButton and then override either mouseDown: or setState: (looking for "NSOnState", which signifies the button is either selected or being pressed on).

查看更多
该账号已被封号
3楼-- · 2019-06-18 16:53

I ended up checking the mouseDownFlags on the buttons cell. Don't know if it's the "right" way to do it, so let me know if you have a better suggestion. Solution is updated in the question above.

查看更多
戒情不戒烟
4楼-- · 2019-06-18 16:53
if([pBtn state]==NSOnState){
   NSLog(@" button Pressed ")
}else{
   NSLog(@" button not pressed ");

}
查看更多
做自己的国王
5楼-- · 2019-06-18 17:02

I solved this by checking [self isHighlighted].

查看更多
登录 后发表回答