iPad OS 键盘开发

    // 在视图控制器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哈哈哈")
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。