Delegates in swift?

前端 未结 12 1319
天命终不由人
天命终不由人 2020-11-22 03:27

How does one go about making a delegate, i.e. NSUserNotificationCenterDelegate in swift?

12条回答
  •  北海茫月
    2020-11-22 04:07

    DELEGATES IN SWIFT 2

    I am explaining with example of Delegate with two viewControllers.In this case, SecondVC Object is sending data back to first View Controller.

    Class with Protocol Declaration

    protocol  getDataDelegate  {
        func getDataFromAnotherVC(temp: String)
    }
    
    
    import UIKit
    class SecondVC: UIViewController {
    
        var delegateCustom : getDataDelegate?
        override func viewDidLoad() {
            super.viewDidLoad()
         }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
        @IBAction func backToMainVC(sender: AnyObject) {
          //calling method defined in first View Controller with Object  
          self.delegateCustom?.getDataFromAnotherVC("I am sending data from second controller to first view controller.Its my first delegate example. I am done with custom delegates.")
            self.navigationController?.popViewControllerAnimated(true)
        }
    
    }
    

    In First ViewController Protocol conforming is done here:

    class ViewController: UIViewController, getDataDelegate
    

    Protocol method definition in First View Controller(ViewController)

    func getDataFromAnotherVC(temp : String)
    {
      // dataString from SecondVC
       lblForData.text = dataString
    }
    

    During push the SecondVC from First View Controller (ViewController)

    let objectPush = SecondVC()
    objectPush.delegateCustom = self
    self.navigationController.pushViewController(objectPush, animated: true)
    

提交回复
热议问题