开发者

Assign button from another class to a current class selector with cocoa

I instantiate a class and then I try to change the selector of the instantiated class button:

WebViewController *newtab = [[WebViewController alloc] initWithNibName:@"NavigatorNoBottom" bundle:nil];
[[newtab tabsButton]setAction:@selector(addtabs:)]; 

The button tabsbutton is an outlet of the WebViewController class which is directly linked in interface builder. The method -(void)Addtabs:(id)sender is a method in my current class.

But it seems that this code does not work, my button is here but it does nothing when I click on it .

If you need more context 开发者_开发百科don't hesitate. I know this is something maybe very simple but I just bug at it....


Note that -initWithNibName:bundle: does not load the nib file immediately. This means that right after sending it you cannot expect your outlets to be set.

In that line where you send -setAction:, your tabsButton outlet is probably nil.

If WebViewController inherits from NSViewController, you can place that line that sets the action in the -loadView method of your WebViewController class to make sure the nib file has been loaded and all outlets are set:

- (void)loadView {
    [super loadView];
    [tabsButton setAction:@selector(addtabs:)];
    // or [self.tabsButton setAction:@selector(addtabs:)]; 
}

Alternatively, if you don’t want to do this inside the view controller, you can do the following in an arbitrary class:

WebViewController *newtab = [[WebViewController alloc] initWithNibName:@"NavigatorNoBottom"
    bundle:nil];
[newtab view];
[[newtab tabsButton]setAction:@selector(addtabs:)]; 

By sending -view to the view controller, you force it to load the nib file, hence the tabsButton outlet will have been set right after that.

Note that you can set the action in any class since a selector is not tied to a class. Also note that, since you haven’t set a target, the action will follow the action chain.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜