ios - 如何从 UITextField 中的外部键盘检测“命令+退格”
问题描述
我正在使用旧的添加零长度字符解决方案来检测空文本字段中的退格(在 UITextField 中检测退格事件)。
不幸的是,在 iPad 上,如果您连接外部键盘并点击“cmd+backspace”,它不会触发 shouldChangeCharactersInRange 方法。
我查看了文档和反编译的标头,但似乎无法找到防止这种情况发生的方法。
那么,如何检测“命令+退格事件”?
解决方案
您可以使用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。
推荐阅读
- bash - 如果上一个命令成功完成,当上一个命令已经运行时,运行命令的简洁方法
- java - .class 文件与 Intellij 和 javac 的区别
- binary-search-tree - 这是最优二叉搜索树吗?
- c++ - 函数(通过 std::move)返回的 unique_ptr 何时超出范围
- javascript - 在 AJAX 和 php 文件之间解析 JSON 数据
- firebase - 我如何将 Pagination 3 与 Firestore 一起使用?
- javascript - 如何 document.querySelectorAll() 仅检查项目
- python - 添加两个数据框行?
- google-apps-script - 为幻灯片设置特定 ID
- python-3.x - Discord.py 机器人多次发送消息