Set Button selector (on click event) at runtime ? (Cocoa : Mac Project)

旧时模样 提交于 2019-12-20 04:11:02

问题


Any idea how to set button selector at runtime (on click event) for mac (Not IOS)

I have a view controller with a button declared as outlet :

#import <Cocoa/Cocoa.h>

@interface MyView : NSView
@property (assign) IBOutlet NSButton *MyBtn;

i can access that buton with something like this :

MyView * v;
.
.
.
[v MyBtn]

i didn't find "addTarget" choice like on cocoa touch. The only choice is "setTarget(id)"

I'm using Xcode 4.4.1 for osx mountain lion

any suggestion would be appreciated. thanks


回答1:


You shall look at the NSControl class reference (from which NSButton inherits) for two separate methods setTarget: and setAction:.

You can do something like this in your code:

[MyBtn setTarget:self];
[MyBtn setAction:@selector(doStuff)];

take a look also at this answer.




回答2:


those two methods are what you are looking for.

  • (void)setTarget:(id)target;
  • (void)setSelector:(SEL)selector;

================

[myButton setSelector:@selector(myButtonClickEvent:)];


-(void) myButtonClickEvent:(id) sender{
       NSLog(@"button:%@ be clicked. :)", sender);
}


来源:https://stackoverflow.com/questions/12234485/set-button-selector-on-click-event-at-runtime-cocoa-mac-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!