iPad OS 键盘开发

2020-10-30  本文已影响0人  菊上一枝梅
    // 在视图控制器Controller中
    // iPad OS键盘事件
    // 重写系统方法return true
    override var canBecomeFirstResponder: Bool {
        return true
    }
    
    // 在控制器的viewDidAppear方法中让当前控制器成为焦点
    override func viewDidAppear(_ animated: Bool) {
        becomeFirstResponder()
    }
    
    // =============================
    // 键盘的按下
    override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
        for press in presses {
            guard let key = press.key?.characters else {
                continue
            }
            switch key {
            case "w":
                DebugLog("w")
            case "a":
                DebugLog("a")
            case "s":
                DebugLog("s")
            case "d":
                DebugLog("d")
            default:
                DebugLog("do nothing")
            }
        }
    }
    
    // 键盘的弹起
    override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
        for press in presses {
            guard let key = press.key?.characters else {
                continue
            }
            switch key {
            case "w":
                DebugLog("w")
            case "a":
                DebugLog("a")
            case "s":
                DebugLog("s")
            case "d":
                DebugLog("d")
            default:
                DebugLog("do nothing")
            }
        }
    }
    
    // =============================
    // 重写一些系统级快捷键的方法,例如此方法为 command + a 全选
    override func selectAll(_ sender: Any?) {
        DebugLog("点击了全选")
    }
    
    // =============================
    // return方法为按键组合
    override var keyCommands: [UIKeyCommand]? {
        // 此方法设置按钮组合,会一直调用方法
        let keyCommand = UIKeyCommand(input: "a", modifierFlags: .control, action: #selector(test))
        // 设置此键值,按键组合只响应一次方法
        keyCommand.setValue(NSNumber.init(value: false), forKey: "repeatable")
        return [
            keyCommand
        ]
    }
    
    // 测试方法
    @objc func test () {
        DebugLog("111哈哈哈")
    }
上一篇 下一篇

猜你喜欢

热点阅读