首页 > 解决方案 > 如何从 UITextField 中的外部键盘检测“命令+退格”

问题描述

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

不幸的是,在 iPad 上,如果您连接外部键盘并点击“cmd+backspace”,它不会触发 shouldChangeCharactersInRange 方法。

我查看了文档和反编译的标头,但似乎无法找到防止这种情况发生的方法。

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

标签: iosuitextfield

解决方案


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

这是操场代码:

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。


推荐阅读