2017-04-19 127 views
1

我目前正在为我正在处理的应用程序制作自定义的UIView类,并且它要求您传递一个将在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(); 
    } 
} 

如何完成我在此尝试完成的操作?

任何及所有的帮助感激

+0

因为类型你的'private var _tapListener'是错误的。 – matt

回答

1

考虑使用瓶盖:

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() 
    } 
} 
+2

您的_tapListener签名不正确。它有Void类型。 – Brandon

+0

@Brandon谢谢你指出。编辑它并删除未使用的伊娃。 – janusbalatbat

+0

这是一个非常好的和详细的答案。谢谢! –

2

就以同样的方式作为参数的实例变量定义到init

private var _tapListener:() -> Void 
+0

这是一个非常简单的解决方案!看起来我有一些阅读关于真正封闭的事情。 –

相关问题