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

标签 ios swift function parameters listeners

我目前正在为我正在开发的应用制作一个自定义 UIView 类,它要求您传递一个 void,该 void 将在 UIView 的点击事件时执行。我需要做的是获取传递给 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();
    }
}

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

非常感谢任何帮助

最佳答案

只需以与init 的参数相同的方式定义您的实例变量:

private var _tapListener: () -> Void

关于ios - 将函数传递给变量,以便稍后调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43507881/

相关文章:

ios - 在标签栏中滚动功能很奇怪

ios - 为什么我看不到我的导航栏项目?

python - 为什么我得到 'None'

ios - 当我运行我的应用程序时,我收到此错误。线程 1 : Fatal error: Unexpectedly found nil while unwrapping an Optional value

ios - 打开动态链接时如何重定向到某个屏幕?

switch-statement - 无法分配给 'let' 值 'action'

r - 将数据帧拆分为包含一对的较小数据帧列表

javascript - 使用 jquery 检查数组中的项目数

ios - 在 NSRegularExpression 模式中使用捕获组

ios - 在推送过渡期间响应导航栏高度变化