iOS Interview: Delegation Pattern in Swift

in #ios6 years ago (edited)

It's a continuation of my previous post about implementing delegate pattern in iOS. This time it is written in Swift.

App Delegate

import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, TapProtocol{
    func buttonTapped() {
        print("Button Tapped")
    }
    
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        if let w =  self.window,let vc = w.rootViewController as? ViewController
        {
            vc.delegate = self
        }
        return true
    }
}

View Controller

protocol TapProtocol:class {
    func buttonTapped()
}

class ViewController: UIViewController {
    weak var delegate:TapProtocol?

    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    @IBAction func buttonTapped(_ sender: Any) {
        self.delegate?.buttonTapped()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Coin Marketplace

STEEM 0.21
TRX 0.20
JST 0.034
BTC 99341.76
ETH 3285.44
USDT 1.00
SBD 3.05