2015-02-22 13 views
5

मेरे पास एक UITapGestureRecognizer से जुड़ा एक कस्टम UIView है।क्या आईओएस में किसी अन्य फ़ंक्शन से ब्लॉक समापन हैंडलर को कॉल करना संभव है?

func hide(sender:UITapGestureRecognizer){ 
    if let customView = sender.view as? UICustomView{ 
     customView.removeFromSuperview() 
    } 
} 

UICustomView भी एक विधि शो() है कि यह एक subview के रूप कहते है, जैसे::

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) 
} 
इशारा पहचानकर्ता एक विधि कहा जाता छिपाने() जैसे superview से देखने को हटाने के लिए कॉल

इसका मतलब है कि मैं एक UICustomView बना सकते हैं और इस तरह के रूप में प्रदर्शित कर सकते हैं:

let testView = UICustomView(frame:frame) 
testView.show() // The view appears on the screen as it should and disappears when tapped 

अब, मुझे लगता है कि कहा जाता है एक पूरा होने के ब्लॉक के साथ एक विधि में मेरी शो() विधि चालू करना चाहते हैं जब छिपाने () समारोह ट्रिगर किया गया है। कुछ की तरह:

testView.show(){ success in 
    println(success) // The view has been hidden 
} 

लेकिन ऐसा करने के लिए इसलिए मैं अपने छिपाने() विधि से विधि शो() के पूरा होने के हैंडलर फोन करना होगा। क्या यह संभव है या क्या मैं कुछ दिख रहा हूं?

उत्तर

8

चूंकि आप 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 एक जीवन चक्र है: viewDidAppear, viewDidDisappear, आदि के रूप में अपने UICustomView है UIView का एक उपवर्ग आप जीवन चक्र तरीकों में से एक रद्द कर सकते थे:

class UICustomView : UIView { 
    // ... 

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

आप सोच सकते हैं इस दूसरा दृष्टिकोण यदि दृश्य hide() पर w/oa कॉल गायब हो सकता है लेकिन आप अभी भी onHide चलाने के लिए चाहते हैं।

+2

चालाक! और एक आकर्षण की तरह काम करता है, धन्यवाद @GoZoner :) – Audioy

संबंधित मुद्दे

 संबंधित मुद्दे