UIButton parameterized action selector for a method in another class?

This is largely a syntax issue. How to set a UIButton action selector to call a method of another class? I made a #import class, the methods of which I need to call using the button, and I have the following partial understanding of how the button code should look:

UIButton *btnSplash = [UIButton buttonWithType:UIButtonTypeRoundedRect]; btnSplash.frame = CGRectMake(250, 270, 180, 30); [btnSplash setTitle:@"Menu" forState:UIControlStateNormal]; [btnSplash addTarget:self action:@selector([CLASS METHOD:PARAMETER]) forControlEvents:UIControlEventTouchUpInside]; [self addSubview:btnSplash]; 

However, I get the following errors:

expected ':' before '[' token

method name is missing in @selector

The sample code that I saw in the help library calls local methods, so I'm trying to generalize, and my attempts have so far been fruitless.

thanks

+4
source share
1 answer

A selector is a representation of the name of a method, regardless of which classes or categories implement it.

Let's say you have a class called AnotherClass that implements the method - (void)doSomething:(id)sender . The corresponding doSomething: selector, represented in the code as @selector(doSomething:) . If you want the button action to call this method, you need to have an instance of AnotherClass - and this instance is the target of the action instead of self . Therefore, your code should have:

 #import "AnotherClass.h" AnotherClass *instanceOfAnotherClass; // assign an instance to instanceOfAnotherClass UIButton *btnSplash = [UIButton buttonWithType:UIButtonTypeRoundedRect]; btnSplash.frame = CGRectMake(250, 270, 180, 30); [btnSplash setTitle:@"Menu" forState:UIControlStateNormal]; [btnSplash addTarget:instanceOfAnotherClass action:@selector(doSomething:) forControlEvents:UIControlEventTouchUpInside]; [self addSubview:btnSplash]; 
+10
source

Source: https://habr.com/ru/post/1347422/


All Articles