Detect backspace in empty UITextField
Asked Answered
P

28

147

Is there any way to detect when the Backspace/Delete key is pressed in the iPhone keyboard on a UITextField that is empty? I want to know when Backspace is pressed only if the UITextField is empty.


Based on the suggestion from @Alex Reynolds in a comment, I've added the following code while creating my text field:

[[NSNotificationCenter defaultCenter] addObserver:self
          selector:@selector(handleTextFieldChanged:)
              name:UITextFieldTextDidChangeNotification
            object:searchTextField];

This notification is received (handleTextFieldChanged function is called), but still not when I press the Backspace key in an empty field. Any ideas?


There seems to be some confusion around this question. I want to receive a notification when the Backspace key is pressed. That's it. But the solution must also work when the UITextField is already empty.

Palua answered 30/12, 2009 at 1:21 Comment(2)
2011/11 solution for empty UITextField using runtime trickery: bjhomer.blogspot.com/2011/11/…Dotterel
For those who are struggling with this in SwiftUI you can find a full example for a real use case here(#76685422)Pelfrey
M
38

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.

Macula answered 30/12, 2009 at 23:10 Comment(8)
Nice. I agree that it's pretty hacky, but I was considering something like this as a last resort. Thanks for the suggestion.Palua
@Andrew, this is the approach I decided to take. It took a bit of code, but it's certainly effective. Thanks for the help instead of trying to tell me that I'm doing something wrong.Palua
This technique may work on iPhone > 3.1.3, but it's hacky and may break on future versions, etc. I think I found a cleaner, more stable solution for how to detect a delete keyboard key press on the iPhone/iOS.Rentroll
Note that you should also remove the space character when the text field is not being edited. Otherwise your placeholder text won't be visible.Norford
I can confirm that delete isn't detected if the user manages to move the cursor to the left of the space. If you can figure out how to fix that, then you should also subclass UITextField and implement canPerformAction:withSender: to return NO for select: and selectAll: actions when the text is equal to the string @"\u200B".Rentroll
^I recall code for being able to detect the user's cursor location... you could search for that and then recall the becomeFirstResponder method if they move the cursor (so it moves back)Cabbage
Problem is that this doesn't work for secure test fields. Any ideas how to handle that?Robby
Sorry, but this idea is bad. It's incredible hacky and shouldn't be the accepted answer with 30 or so upvotes. I would subclass UITextField instead, like some of the other commenters have mentioned.Papilloma
M
188

Swift 4:


Subclass UITextField:

// MyTextField.swift
import UIKit

protocol MyTextFieldDelegate: AnyObject {
    func textFieldDidDelete()
}

class MyTextField: UITextField {

    weak var myDelegate: MyTextFieldDelegate?

    override func deleteBackward() {
        super.deleteBackward()
        myDelegate?.textFieldDidDelete()
    }

}

Implementation:

// ViewController.swift

import UIKit

class ViewController: UIViewController, MyTextFieldDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        // initialize textField
        let input = MyTextField(frame: CGRect(x: 50, y: 50, width: 150, height: 40))

        // set viewController as "myDelegate"
        input.myDelegate = self

        // add textField to view
        view.addSubview(input)

        // focus the text field
        input.becomeFirstResponder()
    }

    func textFieldDidDelete() {
        print("delete")
    }

}

Objective-C:


Subclass UITextField:

//Header
//MyTextField.h

//create delegate protocol
@protocol MyTextFieldDelegate <NSObject>
@optional
- (void)textFieldDidDelete;
@end

@interface MyTextField : UITextField<UIKeyInput>

//create "myDelegate"
@property (nonatomic, assign) id<MyTextFieldDelegate> myDelegate;
@end

//Implementation
#import "MyTextField.h"

@implementation MyTextField

- (void)deleteBackward {
    [super deleteBackward];

    if ([_myDelegate respondsToSelector:@selector(textFieldDidDelete)]){
        [_myDelegate textFieldDidDelete];
    }
}

@end

Now simply add MyTextFieldDelegate to your UIViewController and set your UITextFields myDelegate to self:

//View Controller Header
#import "MyTextField.h"

//add "MyTextFieldDelegate" to you view controller
@interface ViewController : UIViewController <MyTextFieldDelegate>
@end

//View Controller Implementation
- (void)viewDidLoad {
    //initialize your text field
    MyTextField *input = 
     [[MyTextField alloc] initWithFrame:CGRectMake(0, 0, 70, 30)];

    //set your view controller as "myDelegate"
    input.myDelegate = self;

    //add your text field to the view
    [self.view addSubview:input];
}

//MyTextField Delegate
- (void)textFieldDidDelete {
    NSLog(@"delete");
}
Macy answered 4/4, 2013 at 1:52 Comment(3)
What will happen to my existing delegate methods in ViewController class if I set my textfield's delegate to subclass of UITextField instead of UIViewControllerEclipse
deleteBackward() won't be called if you return false in textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> BoolMichaella
For the called method (textFieldDidDelete) is there a non-hacky way to do something only when the text view (in my case) was already empty? I am using it to delete a row in a table but only when tapping backspace in an empty text view. My hacky solution is adding a bool to check. So the first time the text view is empty it changes the bool. The next time it deletes. (without the bool it deletes any time the text view is empty)Embroideress
R
41

Update: See JacobCaraballo's answer for an example that overrides -[UITextField deleteBackward].

Check out UITextInput, specifically UIKeyInput has a deleteBackward delegate method that always gets called when the delete key is pressed. If you're doing something simple, then you might consider just subclassing UILabel and making it conform to the UIKeyInput protocol, as done by SimpleTextInput and this iPhone UIKeyInput Example. Note: UITextInput and its relatives (including UIKeyInput) are only available in iOS 3.2 and later.

Rentroll answered 9/7, 2011 at 22:14 Comment(0)
M
38

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.

Macula answered 30/12, 2009 at 23:10 Comment(8)
Nice. I agree that it's pretty hacky, but I was considering something like this as a last resort. Thanks for the suggestion.Palua
@Andrew, this is the approach I decided to take. It took a bit of code, but it's certainly effective. Thanks for the help instead of trying to tell me that I'm doing something wrong.Palua
This technique may work on iPhone > 3.1.3, but it's hacky and may break on future versions, etc. I think I found a cleaner, more stable solution for how to detect a delete keyboard key press on the iPhone/iOS.Rentroll
Note that you should also remove the space character when the text field is not being edited. Otherwise your placeholder text won't be visible.Norford
I can confirm that delete isn't detected if the user manages to move the cursor to the left of the space. If you can figure out how to fix that, then you should also subclass UITextField and implement canPerformAction:withSender: to return NO for select: and selectAll: actions when the text is equal to the string @"\u200B".Rentroll
^I recall code for being able to detect the user's cursor location... you could search for that and then recall the becomeFirstResponder method if they move the cursor (so it moves back)Cabbage
Problem is that this doesn't work for secure test fields. Any ideas how to handle that?Robby
Sorry, but this idea is bad. It's incredible hacky and shouldn't be the accepted answer with 30 or so upvotes. I would subclass UITextField instead, like some of the other commenters have mentioned.Papilloma
P
32

Code like following:

@interface MyTextField : UITextField
@end

@implementation MyTextField

- (void)deleteBackward
{
    [super deleteBackward];

    //At here, you can handle backspace key pressed event even the text field is empty
}

@end

At last, do forget to change the Custom Class property of the Text Field to "MyTextField"

Parham answered 24/4, 2013 at 2:41 Comment(0)
C
23

Swift implementation:

import UIKit

// Extend from PinTextFieldDelegate instead of UITextFieldDelegate in your class
protocol PinTextFieldDelegate : UITextFieldDelegate {
    func didPressBackspace(_ textField: PinTextField)
}

class PinTextField: UITextField {

    override func deleteBackward() {
        super.deleteBackward()

        // If conforming to our extension protocol
        if let pinDelegate = self.delegate as? PinTextFieldDelegate {
            pinDelegate.didPressBackspace(self)
        }
    }
}
Carnes answered 6/1, 2017 at 2:46 Comment(1)
Thanks, may i know this method is recommended by apple or it's hack. it seems undocumented for textfield.Freighter
D
18

I've founded other way easier than subclass solution. Even its little bit strange but it works ok.

- (BOOL)textView:(UITextView *)textView 
        shouldChangeTextInRange:(NSRange)range 
        replacementText:(NSString *)text
{
    const char * _char = [text cStringUsingEncoding:NSUTF8StringEncoding];
    int isBackSpace = strcmp(_char, "\b");

    if (isBackSpace == -8) {
       // is backspace
    }

    return YES;
}

It's a little bit strange for result of compare is -8. Maybe I'll wrong in some point of C Programming. But its right work ;)

Dichasium answered 20/2, 2012 at 3:33 Comment(5)
Backstroke isn't '\b' set. But if you carefully debugging then you will see '\0'. So I get the result 0 that is two values are equal in strcmp method. const char *stoke = [text cStringUsingEncoding:NSASCIIStringEncoding]; const char *backstroke = "\0";// this is equal to \b->"\x08"; strcmp(backstroke, stoke);Chancelor
Also, by the definition of strcmp(s1, s2), returns 0 if s1 == s2, > 0 s1 is has lexicographically greater than s2 vice versa.Chancelor
I don't understand how this could possibly work? @YoonLee: aren't you saying strcmp returns either -1, 0, or 1? That was my understanding.Oxblood
in textview you always detect the backspace even if the there's no text, the UITextField is differentPhytohormone
This is a UITextViewDelegate method, not UITextFieldDelegate.Lamellicorn
P
13

please use below code it will help you to detect keyboard delete key even if you textfield is empty.

Objective C :

- (BOOL)keyboardInputShouldDelete:(UITextField *)textField { return YES; }

Swift :

func keyboardInputShouldDelete(_ textField: UITextField) -> Bool { return true }
Pule answered 5/6, 2017 at 11:36 Comment(3)
Tx - just what I needed. But where is it documented??Buehrer
absolutely best answer. This method is called only when back button is pressed on an empty text fieldRanda
there's a consideration though. this method is not documented anywhere. Therefore here we rely on some private iOS stuff. Which is not goodRanda
I
11

Try the delegate

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

Then check if the range.length == 1 which seems to be the case when backspace is hit.

Information answered 16/4, 2010 at 16:1 Comment(1)
Only called when field is non-empty, though. Note the original question. :)Impossibility
S
9

Niklas Alvaeus's answer helped me out with a similar issue

I was limiting entry to a specific character set, but it was ignoring backspaces. So I had it check range.length == 1 before trimming the NSString. If it is true, I just return the string and don't trim it. See below

 - (BOOL) textField:(UITextField *)textField 
          shouldChangeCharactersInRange:(NSRange)range 
          replacementString:(NSString *)string
 {
     NSCharacterSet *nonNumberSet = 
      [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] 
         invertedSet];

    if (range.length == 1) {
       return string;
    }
    else {
       return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);
    }   
 }
Seidler answered 30/4, 2010 at 13:8 Comment(1)
The method expects a boolean and not a string as return valueMudslinging
P
5

Yup, use below method to detect backspace, when textField is empty.

Need to add UITextFieldDelegate

yourTextField.delegate = self (MUST REQUIRED)

Swift:

func keyboardInputShouldDelete(_ textField: UITextField) -> Bool { 
    return true
}

Objective C:

- (BOOL)keyboardInputShouldDelete:(UITextField *)textField { 
    return YES; 
}
Puglia answered 26/7, 2017 at 12:54 Comment(3)
This doesn't even call for me. All other delegate methods are getting called as and when for an event occurs.Cistern
@McDonal_11 I think you forgot to set textfield.delegate = self of textfield.Puglia
I have set. other UITextField's delegate methods are working fine. This one alone not working. What I miss ??Responser
P
4

For the ones who has problems about the Jacob's answer I implemented my textfield subclass as following and it works great!

#import <UIKit/UIKit.h>

@class HTTextField;

@protocol HTBackspaceDelegate <NSObject>

@optional
- (void)textFieldDidBackspace:(HTTextField*)textField;
@end

@interface HTTextField : UITextField<UIKeyInput>

@property (nonatomic, assign) id<HTBackspaceDelegate> backspaceDelegate;

@end


#import "HTTextField.h"

@implementation HTTextField

- (void)deleteBackward {
    [super deleteBackward];
    if ([self.backspaceDelegate respondsToSelector:@selector(textFieldDidBackspace:)]){
        [self.backspaceDelegate textFieldDidBackspace:self];
    }
}

- (BOOL)keyboardInputShouldDelete:(UITextField *)textField {
    BOOL shouldDelete = YES;

    if ([UITextField instancesRespondToSelector:_cmd]) {
        BOOL (*keyboardInputShouldDelete)(id, SEL, UITextField *) = (BOOL (*)(id, SEL, UITextField *))[UITextField instanceMethodForSelector:_cmd];

        if (keyboardInputShouldDelete) {
            shouldDelete = keyboardInputShouldDelete(self, _cmd, textField);
        }
    }

    if (![textField.text length] && [[[UIDevice currentDevice] systemVersion] intValue] >= 8) {
        [self deleteBackward];
    }

    return shouldDelete;
}

@end
Pulpy answered 20/10, 2014 at 20:46 Comment(1)
can you write the code for swift. I got some error "redundant confirmance to protoco uikeyinput"Delatorre
K
3

The best use that I have found for detecting backspace is detecting when the user has pressed backspace in an empty UITextField. For example, if you have 'bubbled' recipients in the mail app, when you hit backspace in the UITextField, it selects the last 'bubbled' recipient.

This can be done in a similar way to Jacob Caraballo's answer. But in Jacob's answer, if the UITextField has one character left when you hit backspace, by the time the delegate message is received, the UITextField will already be empty, so you're effectively detecting backspace on a text field with at most one characters.

Actually, if you want to detect backspace on a UITextField with exactly zero characters (empty), then you should send the message to the delegate before the call to super deleteBackward. For example:

#import "MyTextField.h"

//Text field that detects when backspace is hit with empty text
@implementation MyTextField

#pragma mark - UIKeyInput protocol
-(void)deleteBackward
{
  BOOL isTextFieldEmpty = (self.text.length == 0);
  if (isTextFieldEmpty) {
    if ([self.delegate 
         respondsToSelector:@selector(textFieldDidHitBackspaceWithEmptyText:)]) {

        [self.delegate textFieldDidHitBackspaceWithEmptyText:self];
        }
    }
    [super deleteBackward];
}
@end

The interface for such a text field would look something like this:

@protocol MyTextFieldDelegate;

@interface MyTextField : UITextField
@property(nonatomic, weak) id<MyTextFieldDelegate> delegate;
@end

@protocol MyTextFieldDelegate <UITextFieldDelegate>
@optional
-(void)textFieldDidHitBackspaceWithEmptyText:(MyTextField *)textField;
@end
Keck answered 11/7, 2013 at 17:39 Comment(1)
In order for this to work in iOS8 (where there's a bug causing this delegate method never to be called), please see this answer: https://mcmap.net/q/160732/-how-to-detect-delete-key-on-an-uitextfield-in-ios-8 . More details on the ios8 bug: devforums.apple.com/message/1009150#1009150Pistoleer
P
2

In iOS 6, the deleteBackward method is called on the UITextField when backspace is pressed, including when the field is empty. So you can subclass UITextField and provide your own deleteBackward implementation (invoking super's as well.)

I'm still supporting iOS 5 though so I'll need a combination of Andrew's answer and this.

Push answered 22/10, 2012 at 18:28 Comment(0)
D
2

In .h file add UIKeyInput delegate

- (BOOL)keyboardInputShouldDelete:(UITextField *)textField {

if ([textField isEqual:_txtFirstDigit]) {

}else if([textField isEqual:_txtSecondDigit]) {
    [_txtFirstDigit becomeFirstResponder];

}else if([textField isEqual:_txtThirdDigit]) {
    [_txtSecondDigit becomeFirstResponder];

}else if([textField isEqual:_txtFourthDigit]) {
    [_txtThirdDigit becomeFirstResponder];
}
return YES;
}   

improved Formatting

Dorm answered 16/3, 2018 at 7:1 Comment(0)
N
1

:) just for the title "Detect backspace", where I use UIKeyboardTypeNumberPad.

I also meet the same question tonight, and following is my code to find it out:

- (BOOL)textField:(UITextField *)textField 
        shouldChangeCharactersInRange:(NSRange)range 
        replacementString:(NSString *)string
{
    NSLog([NSString stringWithFormat:@"%d", [string length]]);
}

Because with UIKeyboardTypeNumberPad, user can only input Number or backspace, so when the length of string is 0, it must be backspace key.

Hope the above will do some help.

Northrup answered 26/12, 2011 at 12:55 Comment(2)
It's the same with any keyboard type.Rentroll
how do i hook this method up to my text field?Valuator
J
1

Rather than trying to preconstruct what WILL BE in the text field or figure out what special character has been entered in the shouldChangeCharactersInRange method, I would suggest doing the following:

[self performSelector:@selector(manageSearchResultsDisplay) 
           withObject:nil 
           afterDelay:0];

This allows you to call a method directly after the current operation completes. What's cool about this is that, by the time it completes, the modified value will already be in the UITextField. At that point, you can just check its length and/or validate based on what's there.

Jin answered 4/12, 2012 at 20:19 Comment(0)
T
1

Subclassing UITextField did not work for me on iOS 8.3, deleteBackward was never called.

Here is the solution I used, works on all iOS 8 versions and should work on other iOS versions as well

for textField in textFields {
            textField.text = " "
}

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        if string == "" && textField.text == " "   {
            // Do stuff here
            return false
        }
        return true
}
Tangency answered 20/5, 2015 at 20:26 Comment(0)
C
1

I have implemented the similar solution with minor improvements that will tell me that if the text field has any value while the user has tapped the backspace. This is useful for my case when I should only focus on another text field if the text field is empty when backspace pressed.

protocol MyTextFieldDelegate : UITextFieldDelegate {
    func textFieldDidDelete(textField: MyTextField, hasValue: Bool)
}

override func deleteBackward() {
    let currentText = self.text ?? ""
    super.deleteBackward()
    let hasValue = currentText.isEmpty ? false : true
    if let delegate = self.delegate as? MyTextFieldDelegate {
        delegate.textFieldDidDelete(textField: self, hasValue: hasValue)
    }
}
Cistern answered 21/5, 2018 at 8:7 Comment(0)
B
1

The most poplar answer is missing one thing — the ability to detect whether the text field was empty or not.

That is, when you override the deleteBackwards() method of a TextField subclass, you still don't know whether the text field was already empty. (Both before and after deleteBackwards(), textField.text! is an empty string: "")

Here's my improvement, with a check for emptiness prior to deletion.

1. Create a delegate protocol that extends UITextFieldDelegate

protocol MyTextFieldDelegate: UITextFieldDelegate {
    func textField(_ textField: UITextField, didDeleteBackwardAnd wasEmpty: Bool)
}

2. Subclass UITextField

class MyTextField: UITextField {
    override func deleteBackward() {
        // see if text was empty
        let wasEmpty = text == nil || text! == ""

        // then perform normal behavior
        super.deleteBackward()

        // now, notify delegate (if existent)
        (delegate as? MyTextFieldDelegate)?.textField(self, didDeleteBackwardAnd: wasEmpty)
    }
}

3. Implement your new delegate protocol

extension MyViewController: MyTextFieldDelegate {
    func textField(_ textField: UITextField, didDeleteBackwardAnd wasEmpty: Bool) {
        if wasEmpty {
            // do what you want here...
        }
    }
}
Bayer answered 15/1, 2019 at 21:50 Comment(0)
H
1

Comprehensive handler for textfield with single digit number for Swift 5.1:

  • Assuming that you have outlet collection of textFields (with connected delegates as well)

1 Step

protocol MyTextFieldDelegate: class {
    func textField(_ textField: UITextField, didDeleteBackwardAnd wasEmpty: Bool) 
}

final class MyTextField: UITextField {

    weak var myDelegate: MyTextFieldDelegate?

    override func deleteBackward() {
        let wasEmpty = text == nil || text == ""

        // then perform normal behavior
        super.deleteBackward()

        // now, notify delegate (if existent)
        (delegate as? MyTextFieldDelegate)?.textField(self, didDeleteBackwardAnd: wasEmpty)
    }
}

2 Step

final class ViewController: UIViewController {

    @IBOutlet private var textFields: [MyTextField]!

    override func viewDidLoad() {
        super.viewDidLoad()
        textFields.forEach {
            $0.delegate = self
            $0.myDelegate = self
        }
    }
}

3 Step

extension ViewController: UITextFieldDelegate, MyTextFieldDelegate {
    func textFieldHasChanged(with text: String, _ tag: Int, for textField: UITextField) {
        textField.text = text

        if let someTextField = (textFields.filter { $0.tag == tag }).first {
            someTextField.becomeFirstResponder()
        } else {
            view.endEditing(true)
        }
    }

    func textField(_ textField: UITextField, didDeleteBackwardAnd wasEmpty: Bool) {
        // If the user was pressing backward and the value was empty, go to previous textField
        textFieldHasChanged(with: "", textField.tag - 1, for: textField)
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // Restrict to only digits
        let aSet = NSCharacterSet(charactersIn: "0123456789").inverted
        let compSepByCharInSet = string.components(separatedBy: aSet)
        let numberFiltered = compSepByCharInSet.joined(separator: "")

        guard string == numberFiltered, let text = textField.text else { return false }

        if text.count >= 1 && string.isEmpty {
            // If the user is deleting the value
            textFieldHasChanged(with: "", textField.tag - 1, for: textField)
        } else {
            textFieldHasChanged(with: string, textField.tag + 1, for: textField)
        }

        return false
    }
}
Hernia answered 15/12, 2019 at 0:32 Comment(0)
S
1

Here my solution based on @andrew idea:

somewhere, for example in viewDidLoad

        textField.delegate = self
        textField.addTarget(self, action: #selector(valueChanged(_:)), for: .editingDidBegin)

and then

    @objc func valueChanged(_ textField: UITextField) {
        textField.text = "\u{200B}"
    }

    override func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        textField.text = string
        if string == "" {
            //backpaspace pressed 
        }
Sophy answered 16/12, 2019 at 9:20 Comment(0)
N
0

All the answers are very helpful and I don't know why everyone is taking the protocol route. You can do it with much less code with call back function like-

Swift 5.0 or above

  1. Make a custom textfield class extending the UITextField and override the deleteBackward function-

    class CustomTextField: UITextField {

     var backButtonPressedInEmptyTextField: (()->())?
    
     override func deleteBackward() {
         super.deleteBackward()
         if let text = self.text, text.count == 0{
             backButtonPressedInEmptyTextField?()
             print("Back space clicked when textfield is empty")
         }
     }
    

    }

  2. Let's assume you want to do something based on that in your ViewController, MyViewController. So, in the MyViewController, just do following-

    class MyViewController: UIViewController{ @IBOutlet weak var sampleTextField: CustomTextField!{ didSet{ sampleTextField.backButtonPressedInEmptyTextField = backButtonPressed() } }

     func backButtonPressed(){
         //do whatever you want
     }
    

    }

I feel with closure or call-back function, it is much cleaner.

Norwegian answered 24/2, 2021 at 11:49 Comment(0)
D
-2

Something like this:

- (BOOL)textField:(UITextField *)textField 
        shouldChangeCharactersInRange:(NSRange)range 
        replacementString:(NSString *)string       
{  
    if (![text hash] && ![textField.text length])  
        [self backspaceInEmptyTextField];  
}

of course the hash is for one character string.

Dovekie answered 2/8, 2012 at 3:25 Comment(0)
H
-2

Using the TextField Delegate method:

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

Add the following code in above method to detect delete event

if(textField == YourTextField)
{
    if ([string length] == 0 && range.length > 0)
    {
        // Your Code after deletion of character
    }
}
Heifetz answered 2/7, 2014 at 9:8 Comment(0)
C
-3
+ (BOOL)detectBackspaceOnly:(NSString *)string
{
    for(int i=0 ; i<string.length ; i++){
        unichar caract = [string characterAtIndex:i];
        if(caract != ' ' && caract != '\n')
            return NO;
    }

    return YES;
}
Cowpea answered 21/3, 2014 at 10:33 Comment(1)
Maybe a little explanation where to put this?Audra
E
-3

You can check the text of the text view/field to see if it's empty and make sure the replacement text is also empty in the shouldChangeTextIn delegate method.

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if (textView.text == "" && text == "") {
        print("Backspace on empty text field.")
    }
    return true
}
Electrical answered 25/7, 2020 at 21:32 Comment(0)
N
-4

In UITextViewDelegate:

- (BOOL)               textView:(UITextView *)textView 
        shouldChangeTextInRange:(NSRange)range 
                replacementText:(NSString *)text
{
    if(text isEqualToString:@"");
    {
        NSLog(@"press backspace.");
    }
}

it works ok for me.

update for Chinese simplified pinyin and Chinese handwriting input:

- (BOOL)               textView:(UITextView *)textView 
        shouldChangeTextInRange:(NSRange)range 
                replacementText:(NSString *)text
{
    if (range.length > 0 && [text isEqualToString:@""]) {
        NSLog(@"press Backspace.");
    }
    return YES;
}

base on the document says:

"If the user presses the deleteKey, the length of the range is 1 and an empty string object replaces that single character."

Nadenenader answered 30/3, 2013 at 6:59 Comment(1)
This question is about UITextField, not UITextView.Rentroll
A
-4

To Keep it Simple here is the only condition u need to check

     if (range.length==1)
Admissible answered 5/6, 2013 at 5:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.