I am using the good old add a zero length character solution to detect backspaces in an empty text field ( Detect backspace Event in UITextField ).
Unfortunately on an iPad if you connect an external keyboard and hit "cmd+backspace" it does not trigger the shouldChangeCharactersInRange method.
I looked around the documentation and the decompiled headers and I don't seem to be able to find a way to prevent that.
So, how do I detect a "command + backspace event"?
You can use a UIKeyCommand
. I tested on my 10.5" iPad Pro running iOS 12.1.1, using a Bluetooth keyboard and the Swift Playgrounds app version 2.2.
Here's the playground code:
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
Tap in the text field, then press ⌘⌫ . Each time you press it, the count in the label increases by 1.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.