如何拦截swiftiOS应用的按键事件?
how to intercept key event of swift iOS app?
我删除了AppDelegate.swift
中的@UIApplicationMain
,并写了如下main.swift
,但程序仍然无法触发keyPressed
功能。但是每次按下键都会执行 print("send event2")
。
如何触发 keyPressed
功能?这个程序有问题吗?
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
}
}
我修改'selector'为#selector(swift 3)终于解决了问题,可能是有bug
我删除了AppDelegate.swift
中的@UIApplicationMain
,并写了如下main.swift
,但程序仍然无法触发keyPressed
功能。但是每次按下键都会执行 print("send event2")
。
如何触发 keyPressed
功能?这个程序有问题吗?
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
}
}
我修改'selector'为#selector(swift 3)终于解决了问题,可能是有bug