将函数传递给变量,以便稍后调用它

时间:2017-04-19 23:47:15

标签: ios swift function parameters listeners

我目前正在为我正在处理的应用程序制作一个自定义UIView类,并且它要求您传递将在UIView的tap事件上执行的void。我需要做的是获取传递给init()函数的函数,并将其存储,以便稍后调用。我目前正在处理的代码如下所示:

class CustomUIView: UIView {

    private var _tapListener : Void;

    init (tapListener: () -> Void){
        //Attempt to set _tapListener variable as tap listener does not work :(
        _tapListener = tapListener();
        //Right now it just executes the function :(
        let listener = UITapGestureRecognizer(target: self, action: #selector(callFunction));
        self.addGestureRecognizer(listener)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func callFunction() {
        //Call the function here
        _tapListener();
    }
}

如何才能完成我想在这里做的事情?

非常感谢任何和所有帮助

2 个答案:

答案 0 :(得分:2)

只需使用与typealias tapListenerClosure = () -> Void class CustomUIView: UIView { var tapClosure: tapListenerClosure init (tap: @escaping tapListenerClosure) { self.tapClosure = tap super.init(.... let listener = UITapGestureRecognizer(target: self, action: #selector(callFunction)); self.addGestureRecognizer(listener) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func callFunction() { //Call the function here self.tapClosure() } } 的参数相同的方式定义实例变量:

init

答案 1 :(得分:1)

考虑使用闭包:

ComboBox.Text
相关问题