Erk*_*ken 6 block ios objective-c-blocks swift
我有一个附加了UITapGestureRecognizer的自定义UIView.手势识别器调用一个名为hide()的方法来从superview中删除视图:
func hide(sender:UITapGestureRecognizer){
if let customView = sender.view as? UICustomView{
customView.removeFromSuperview()
}
}
Run Code Online (Sandbox Code Playgroud)
UICustomView还有一个show()方法,可以将其添加为子视图,如下所示:
func show(){
// Get the top view controller
let rootViewController: UIViewController = UIApplication.sharedApplication().windows[0].rootViewController!!
// Add self to it as a subview
rootViewController.view.addSubview(self)
}
Run Code Online (Sandbox Code Playgroud)
这意味着我可以创建一个UICustomView并将其显示为:
let testView = UICustomView(frame:frame)
testView.show() // The view appears on the screen as it should and disappears when tapped
Run Code Online (Sandbox Code Playgroud)
现在,我想将show()方法转换为一个带有完成块的方法,该方法在触发hide()函数时调用.就像是:
testView.show(){ success in
println(success) // The view has been hidden
}
Run Code Online (Sandbox Code Playgroud)
但要这样做,我将不得不从hide()方法调用show()方法的完成处理程序.这可能还是我忽略了什么?
GoZ*_*ner 12
由于您正在实现UICustomView,所以您需要做的就是将"完成处理程序"存储为UICustomView类的一部分.然后在调用时hide()调用处理程序.
class UICustomView : UIView {
var onHide: ((Bool) -> ())?
func show (onHide: (Bool) -> ()) {
self.onHide = onHide
let rootViewController: UIViewController = ...
rootViewController.view.addSubview(self)
}
func hide (sender:UITapGestureRecognizer){
if let customView = sender.view as? UICustomView{
customView.removeFromSuperview()
customView.onHide?(true)
}
}
Run Code Online (Sandbox Code Playgroud)
当然,每个UIView都有一个生命周期:viewDidAppear,viewDidDisappear等等.因为你UICustomView是一个子类,UIView你可以覆盖一个生命周期方法:
class UICustomView : UIView {
// ...
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear (animated)
onHide?(true)
}
}
Run Code Online (Sandbox Code Playgroud)
如果视图可能会在没有调用的情况下消失hide()但您仍想onHide运行,则可以考虑采用第二种方法.
| 归档时间: |
|
| 查看次数: |
1937 次 |
| 最近记录: |