开发者

iPhone add event for a button in different class

I have a view controller let's call it "View Controller A". I have a different class(derived from NSObject and开发者_如何学运维 in .h and .m pair), let's call this class "B". From a function of "B" I am adding a button in "A" using addSubView. The button is getting added but now I want to attach an event to this newly button. I am using

[newButton addTarget:self etc. etc.]

but it isn't working.

I don't want to declare the event in View Controller "A". Is there any way to get rid of this?

Thanks all for reading this..


[newButton addTarget:viewControllerA etc. etc.]

EDIT: More complete version:

[newButton addTarget:viewControllerA action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];

This assumes that class B has a reference to View Controller A named viewControllerA. It also assumes that View Controller A has implemented the method:

- (void)buttonAction:(id)sender;

EDIT 2: So this is what you want:

[newButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];

I assume you already have that and I assume that the reason it doesn't work is because you have a method that looks something like this:

+ (void)addButtonToController:(UIViewController *)controller;

That's a class method. There is no self in a class method. One possible solution is to make it a singleton class and simply change the method to:

- (void)addButtonToController:(UIViewController *)controller;

You would call that method using:

[[ClassB sharedInstance] addButtonToController:controller];

If you don't know how to create a singleton class I could update my answer a third time to include that. :)

EDIT 3: I still think my original answer is the correct one. You don't have to implement - (void)buttonAction:(id)sender; in every controller. You could use inheritance or a category, to have access to this method in every controller without having to implement it for every controller. If you need help with this let me know.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜