【问题标题】:how to intercept key event of swift iOS app?如何拦截swift iOS应用程序的关键事件?
【发布时间】:2016-12-17 09:28:04
【问题描述】:

我删除了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
    }
}

【问题讨论】:

    标签: swift events key uikeycommand


    【解决方案1】:

    我将'selector'修改为#selector(swift 3),终于解决了问题,可能有bug

    【讨论】:

    • " action: #selector(keyPressed(sender:)) " 而不是 "action: Selector(("keyPressed:"))"
    • 你甚至可以像#selector(keyPressed)这样省略参数定义,但请确保在func keyPressed(sender: UIKeyCommand { // ... }之前添加@objc
    猜你喜欢
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    相关资源
    最近更新 更多