如何从UITextField中的外部键盘检测“命令+退格键”

时间:2019-01-15 20:05:42

标签: ios uitextfield

我正在使用旧的添加零长度字符的解决方案来检测空白文本字段(Detect backspace Event in UITextField)中的退格键。

不幸的是,在iPad上,如果您连接外部键盘并按“ cmd +退格键”,则不会触发shouldChangeCharactersInRange方法。

我环顾了文档和decompiled headers,但似乎无法找到防止这种情况的方法。

那么,如何检测“命令+退格事件”?

1 个答案:

答案 0 :(得分:1)

您可以使用UIKeyCommand。我在运行iOS 12.1.1的10.5英寸iPad Pro上使用蓝牙键盘和Swift Playgrounds应用2.2版进行了测试。

这是游乐场代码:

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {
    override func loadView() {
        let command = UIKeyCommand(input: "\u{8}", modifierFlags: .command, action: #selector(ViewController.handleKeyCommand), discoverabilityTitle: "Hello")
        addKeyCommand(command)

        let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
        view.contentMode = .topLeft
        view.backgroundColor = .white

        let stack = UIStackView()
        stack.axis = .vertical
        stack.spacing = 8
        stack.alignment = .fill
        stack.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stack)
        NSLayoutConstraint.activate([
            view.leadingAnchor.constraint(equalTo: stack.leadingAnchor),
            view.trailingAnchor.constraint(equalTo: stack.trailingAnchor),
            view.topAnchor.constraint(equalTo: stack.topAnchor)])

        let textField = UITextField(frame: CGRect(x: 20, y: 20, width: 260, height: 30))
        textField.borderStyle = .roundedRect
        textField.translatesAutoresizingMaskIntoConstraints = false
        stack.addArrangedSubview(textField)

        label.translatesAutoresizingMaskIntoConstraints = false
        stack.addArrangedSubview(label)

        self.view = view
    }

    @objc func handleKeyCommand(_ sender: UIKeyCommand) {
        commandCount += 1
        label.text = "\(commandCount)"
    }

    private var commandCount = 0
    private let label = UILabel()
}

let vc = ViewController()
PlaygroundPage.current.liveView = vc

在文本字段中点击,然后按⌘⌫。每按一次,标签中的计数就会增加1。