简体   繁体   English

将参数传递给功能

[英]Passing a parameter to function

//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 但我无法通过,因为编译器抛出错误“'#selector'的参数未引用'@Objc'方法,属性或初始化程序

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. 正在将参数传递给Function并从中创建选择器。 You can't do this. 你做不到 A selector must have no arguments. 选择器必须没有参数。 So how do you pass the info parameter then? 那么,如何传递info参数呢?

Create a property in your class called selectedCategory : 在您的类中创建一个名为selectedCategory的属性:

var selectedCategory: FitnessCenterModel!

Before you call addTarget , assign info to the above property: 在调用addTarget之前,将info分配给上述属性:

selectedCategory = info

Create another method that calls Function with the parameter. 创建另一个使用参数调用Function方法。

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

Change your addTarget call to use a buttonClicked as a selector: 将您的addTarget调用更改为使用buttonClicked作为选择器:

#selector(buttonClicked)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM