how to intercept key event of swift iOS app?

1.3k views Asked by At

I deleted the @UIApplicationMain in AppDelegate.swiftand wrote the main.swift as below , but the program still can not fire keyPressed function. But executes print("send event2") every keydown.

How to fire keyPressed function? Is something wrong with this program?

import UIKit
import Foundation

class TApplication: UIApplication {
    override func sendEvent(_ event: UIEvent!) {
       super.sendEvent(event)
    }

    override var keyCommands: [UIKeyCommand]? {
      print("send event2") // this is an example
        return [
            UIKeyCommand(input: "1", modifierFlags: [], action: Selector(("keyPressed:")), discoverabilityTitle: “1”),
            UIKeyCommand(input: "2", modifierFlags: .shift, action: Selector("keyPressed:"), discoverabilityTitle: “2”)]
        ]
    }

    func keyPressed(sender: UIKeyCommand) {
        print("keypressed event !!!!!!!!") // this is an example
    }
}
1

There are 1 answers

2
baileymiller2017 On BEST ANSWER

i modify 'selector' to be #selector (swift 3) and finally solved the problem, maybe there was a bug