Search This Blog

Showing posts with label how to add protocol delegate in swift. Show all posts
Showing posts with label how to add protocol delegate in swift. Show all posts

Monday, 9 November 2015

How to use Protocol Delegate in iOS using Swift language

Define Protocol

There are two controllers:
FirstViewController
SecondViewController

I need to notify FirstViewController that SecondViewController ViewDidAppearCalled



import UIKit

//Define Your protocole here after Import

protocol SecondViewControllerDelegate{
      
    //Add a new function
    func SecondViewDidLoadFinished(controller:SecondViewController)

}



class SecondViewController: UIViewController {
   
    
    var delegate:SecondViewControllerDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

    }

override func viewDidAppear(animated: Bool) {
        
        if let delegate = self.delegate{
            delegate.SecondViewDidLoadFinished(self)
        }
    }




First view

import UIKit



class FirstViewController: UIViewController,SecondViewControllerDelegate {

    
    override func viewDidLoad() {
        super.viewDidLoad()

    }


@IBAction func buttonTapped(sender:UIButton){
        
        let mapObject:SecondViewController = SecondViewController()
        mapObject.delegate = self
        self.navigationController?.pushViewController(mapObject, animated: true)   
    }

func SecondViewDidLoadFinished(controller: SecondViewController) {

//Here you will be notified that second view viewDid appear loaded
        
    }