Nonepse
Nonepse

Reputation: 21

Objective-C : Call a method from another class in addTarget:action:forControlEvents

Here is my problem :

I want to assign an Event on an UIButton. I use this method :


- (void)addTarget:(id)target
action:(SEL)action
forControlEvents:(UIControlEvents)controlEvents

like this :


[newsButton addTarget:self
action:@selector(myEvent2)
forControlEvents:UIControlEventTouchUpInside];

newsButton is my UIButton.

If myEvent2 belongs to the class where I am, the code is compiling and executing fine, everybody is happy.

But if myEvent2 belongs to another class I don't succeed to execute it (the project compiles fine).

I tried out to change my code in that way :


MyViewController* test = [[MyViewController alloc] init];
[newsButton addTarget:self
action:@selector([test myEvent2])
forControlEvents:UIControlEventTouchUpInside];

but I get the followings errors :

Expected ':' before '[' token

Method name missing in @selector

Does someone have any solution to my problem ?

Thanks by advance :)

Upvotes: 2

Views: 5929

Answers (3)

hotpaw2
hotpaw2

Reputation: 70673

Another option is to use a redirection method:

- (void)myRedirectHandler {
    [ test myEvent2 ];
}

...

[newsButton addTarget:self
    action:@selector(myRedirectHandler)
    forControlEvents:UIControlEventTouchUpInside];

Upvotes: 0

filipe
filipe

Reputation: 3380

MyViewController* test = [[MyViewController alloc] init];
[newsButton addTarget:test
    action:@selector(myEvent2)
    forControlEvents:UIControlEventTouchUpInside];

Upvotes: 4

Nimrod
Nimrod

Reputation: 5133

You need to change addTarget:self to addTarget:test

Upvotes: 8

Related Questions