How do Responder Chain Works in IPhone? What are the “next responders”?

后端 未结 5 1477
难免孤独
难免孤独 2021-01-31 09:01

This is what the documentation says:

If the first responder [to an event or action message] cannot handle an event or action message, it forwards it to th

5条回答
  •  感情败类
    2021-01-31 09:59

    The responder chain for any event is

    UIView -> ViewController -> Window-> App Delegate

    Run the below code for better understanding.

    //
    //  AppDelegate.swift
    //  ResponderChain
    //
    //  Created by Ankit on 02/09/17.
    //  Copyright © 2017 Ankit. All rights reserved.
    //
    
    import UIKit
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        var window: UIWindow?
    
    
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
            // Override point for customization after application launch.
            return true
        }
    
       override func touchesBegan(_ touches: Set, with event: UIEvent?) {
            print("App Delegate touch began")
        }
    
    
    }
    
    
    
    //
    //  ViewController.swift
    //  ResponderChain
    //
    //  Created by Ankit on 02/09/17.
    //  Copyright © 2017 Ankit. All rights reserved.
    //
    
    import UIKit
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
        override func touchesBegan(_ touches: Set, with event: UIEvent?) {
            print("ViewController touch Began")
            next?.touchesBegan(touches, with: event)
        }
    
    
    }
    
    extension UIWindow{
        open override func touchesBegan(_ touches: Set, with event: UIEvent?) {
            print("Window Touch Began")
            next?.touchesBegan(touches, with: event)
        }
    }
    extension UIView{
        open override func touchesBegan(_ touches: Set, with event: UIEvent?) {
            print("UIView touch Began")
            next?.touchesBegan(touches, with: event)
        }
    }
    

提交回复
热议问题