Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否可以从iOS中的另一个函数调用块完成处理程序?_Ios_Swift_Block_Objective C Blocks - Fatal编程技术网

是否可以从iOS中的另一个函数调用块完成处理程序?

是否可以从iOS中的另一个函数调用块完成处理程序?,ios,swift,block,objective-c-blocks,Ios,Swift,Block,Objective C Blocks,我有一个自定义UIView,附带了一个UIApgestureRecognitor。手势识别器调用一个名为hide()的方法从superview中删除视图,如下所示: func hide(sender:UITapGestureRecognizer){ if let customView = sender.view as? UICustomView{ customView.removeFromSuperview() } } UICustomView还有一个show(

我有一个自定义UIView,附带了一个UIApgestureRecognitor。手势识别器调用一个名为hide()的方法从superview中删除视图,如下所示:

func hide(sender:UITapGestureRecognizer){
    if let customView = sender.view as? UICustomView{
        customView.removeFromSuperview()
    }
}
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)
}   
这意味着我可以创建UICustomView并将其显示为:

let testView = UICustomView(frame:frame) 
testView.show() // The view appears on the screen as it should and disappears when tapped
现在,我想将show()方法转换为一个具有完成块的方法,当hide()函数被触发时,该块将被调用。比如:

testView.show(){ success in
    println(success) // The view has been hidden
}
但要做到这一点,我必须从hide()方法调用show()方法的完成处理程序。
这是可能的还是我忽略了什么?

因为您正在实现
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)
    }
}
当然,每个
UIView
都有一个生命周期:
viewdide出现
viewdide消失
,等等。由于
UICustomView
UIView
的子类,您可以覆盖其中一个生命周期方法:

class UICustomView : UIView {
  // ...

  override func viewDidDisappear(_ animated: Bool) {
     super.viewDidDisappear (animated)
     onHide?(true)
  }
}

您可以考虑第二种方法,如果视图可能会消失到W/O调用<代码> HIDED()/<代码>,但您仍然希望<代码> OnLoo< <代码>运行。