Passing a parameter to function

50 views Asked by At

//This is the function which contain my button action programatically

func didSetCategory(info: FitnessCenterModel) {
    myButton.addTarget(self, action: #selector(Function(d: info)), for: .touchUpInside)    
     }

// my selector function for the button target

func Function(d:FitnessCenterModel ) {
print(info)
}

but i am not able to pass as the compiler is throwing an error "Argument of '#selector' does not refer to an '@Objc' method, property, or initialzer

1

There are 1 answers

7
Sweeper On BEST ANSWER

A selector does not refer to a method call, but just the method itself.

What you are doing here:

#selector(Function(d: info))

is passing an argument to Function and creating a selector from this. You can't do this. A selector must have no arguments. So how do you pass the info parameter then?

Create a property in your class called selectedCategory:

var selectedCategory: FitnessCenterModel!

Before you call addTarget, assign info to the above property:

selectedCategory = info

Create another method that calls Function with the parameter.

func buttonClicked() {
    Function(d: selectedCategory)
}

Change your addTarget call to use a buttonClicked as a selector:

#selector(buttonClicked)