Detect Backspace Event in Uitextfield

Detect backspace in empty UITextField

This may be a long shot but it could work. Try setting the text field's text to a zero width space character \u200B. When backspace is pressed on a text field that appears empty, it will actually delete your space. Then you can just reinsert the space.

May not work if the user manages to move the caret to the left of the space.

Detect backspace Event in UITextField

Swift 4.2

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if let char = string.cString(using: String.Encoding.utf8) {
let isBackSpace = strcmp(char, "\\b")
if (isBackSpace == -92) {
print("Backspace was pressed")
}
}
return true
}

Older Swift version

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let char = string.cStringUsingEncoding(NSUTF8StringEncoding)!
let isBackSpace = strcmp(char, "\\b")

if (isBackSpace == -92) {
println("Backspace was pressed")
}
return true
}

How to detect delete key on an UITextField in iOS 8?

You must look an example for MBContactPicker on github. Deletion of contacts at MBContactPicker via Backspace button on iOS8 tested by me. And it works greatly! You can use its as example.

Author of MBContactPicker use next method: When UITextField must become empty (or before call becomeFirstResponder when it is empty), he save single whitespace symbol there. And then when you press Backspace button (when focus was set to end of text of your UITextField), method

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

will work. Inside it you must use check like this:

NSString *resultString = [textField.text stringByReplacingCharactersInRange:range withString:string];
BOOL isPressedBackspaceAfterSingleSpaceSymbol = [string isEqualToString:@""] && [resultString isEqualToString:@""] && range.location == 0 && range.length == 1;
if (isPressedBackspaceAfterSingleSpaceSymbol) {
// your actions for deleteBackward actions
}

So, you must always control that UITextField contains single whitespace.

This is not hack. So, user willn't noticed about some behaviour was changed

Detect backspace in empty UITextField

This may be a long shot but it could work. Try setting the text field's text to a zero width space character \u200B. When backspace is pressed on a text field that appears empty, it will actually delete your space. Then you can just reinsert the space.

May not work if the user manages to move the caret to the left of the space.

How do I detect a command + backspace from an external keyboard in a UITextField

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.

Detect backspace in empty UITextField Swift Working Sample

If you use Jacob's solution, the deleteBackward method will be called with the current UITextField instance. So you can add a protocol to that UITextField class and pass it back to your view.
Something like this:

protocol MyTextFieldDelegate: class {
func backwardDetected(textField: MyTextField)
}

class MyTextField: UITextField {
weak var myTextFieldDelegate: MyTextFieldDelegate?

override func deleteBackward() {
super.deleteBackward()

self.myTextFieldDelegate?.backwardDetected(textField: self)
}
}

How to detect UIKeyboard backspace button touch on UITextField?

if the UITextField is empty, the shouldChangeTextInRange delegate method is not called
You can subclass UITextField and override this method:

-(void)deleteBackward;
{
[super deleteBackward];
NSLog(@"BackSpace Detected");
}

since UITextField is compliant to the UITextInput protocol, this method is implemented, and you can override it to detect when backspace is pressed.
Then, you can write your own protocol/delegate method to alert your custom textfield delegate if the backspace is detected.



Related Topics



Leave a reply



Submit