iOS Swift Interrupt Keyboard Events

泄露秘密 提交于 2019-12-21 05:30:08

问题


I have problem to intercept keyboard events. I have connected my iOS with SteelSeries Free (gamepad controller) which when connected to iOS will be detected as a Bluetooth Keyboard. This is tested when I open Notes, any button presses in the gamepad will write a letter.

I need to intercept this button presses and run my own functions but unfortunately I am unable to do so.

I've been trying to use GCController but apparently it is not detected as Game Controller object. When I print the count, it shows as 0. My code below.

let gameControllers = GCController.controllers() as! [GCController]
println("configureConnectedGameControllers count: \(gameControllers.count)")

So I assumed it is because the gamepad is detected as bluetooth keyboard that is why its not detected as game controller. And so I attempted to use UIKeyCommand instead. Below is my code:

override func viewDidLoad() {
    super.viewDidLoad()

    var keys = [UIKeyCommand]()
    for digit in "abcdefghijklmnopqrstuvwxyz"
    {
        keys.append(UIKeyCommand(input:  String(digit), modifierFlags: .Command, action:  Selector("keyPressed:")))
        keys.append(UIKeyCommand(input: String(digit), modifierFlags: .Control, action:  Selector("keyPressed:")))
        keys.append(UIKeyCommand(input: String(digit), modifierFlags: nil, action:  "pressKey"))
    }
}

override func canBecomeFirstResponder() -> Bool {
    return true
}

func keyPressed(command: UIKeyCommand) {
    println("another key is pressed") //never gets called
}

func pressKey() {
    println("a key is pressed")
}

But even with the above implementation, nothing is printed in the console when i press a button at the gamepad.

This confuses me. So please help me if you know any answer to this. Thanks in advance!


回答1:


I finally managed to get it working. Below is the code if anyone ever needs it.

var keys = [UIKeyCommand]()

override func viewDidLoad() {
    super.viewDidLoad()
    //configureGameControllers()

    for digit in "abcdefghijklmnopqrstuvwxyz"
    {
        keys.append(UIKeyCommand(input: String(digit), modifierFlags: nil, action:  Selector("keyPressed:")))
    }
}

override func canBecomeFirstResponder() -> Bool {
    return true
}

override var keyCommands: [AnyObject]? {
    get {
        return keys
    }
}


func keyPressed(command: UIKeyCommand) {
    println("user pressed \(command.input)")
}


来源:https://stackoverflow.com/questions/32045170/ios-swift-interrupt-keyboard-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!