Tap on UITextField's clear button hides keyboard instead of clearing text

前端 未结 5 1472
[愿得一人]
[愿得一人] 2021-02-07 03:54

In iPhone, I have a view which has a UITextField. When I tap on the clear button of UITextField\'s the keyboard dismissed instead of clearing the text

相关标签:
5条回答
  • 2021-02-07 04:35

    Try this code after you attach delegate of uitextifield

    -(BOOL)textFieldShouldClear:(UITextField *)textField
    {
         return true;
    }
    
    0 讨论(0)
  • 2021-02-07 04:46

    Just clear the field, resignFirstResponder (if you want to hide keyboard) and return NO/false

    Note: set Attributes inspector property of UITextField

    Clear Button -> Appears while editing

    so it will display the clear button while editing in the text field.

    // Objective-C

    -(BOOL)textFieldShouldClear:(UITextField *)textField
    {
        textField.text = @"";
        [textField resignFirstResponder];
        return NO;
    }
    

    // Swift

    func textFieldShouldClear(textField: UITextField) -> Bool {
        textField.text = ""
        textField.resignFirstResponder()
        return false
    }
    
    0 讨论(0)
  • 2021-02-07 04:46

    Just make sure U've given these two

    editingTextField.delegate = self;
    editingTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    

    TextFieldShouldClear is needed only if you need to do some customizations :-)

    Are you doing some thing in this method?

    Maybe you are are calling resignFirstResponder in this delegate method, thats why the keyboard is getting dismissed.

    Please go through the delegate methods, and check what u r doing exactly.

    0 讨论(0)
  • 2021-02-07 04:46

    This issue happened also if you have

    yourTextField.clearButtonMode = UITextFieldViewModeNever;
    

    Check this line and delete it or change view mode..

    0 讨论(0)
  • 2021-02-07 04:52

    First, check all the code blocks that related to your UITextField (especially the code yourTextField.hidden = YES;)

    Put break points and analyze every UITextField delegates that you implemented.

    (textFieldDidEndEditing,textFieldShouldEndEditing,textFieldShouldReturn.etc.)

    OR

    Implement the textFieldShouldClear delegate and write the code here to visible and clear your UITextField

    To do this, you have to set the clearButtonMode as below,

    yourTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    yourTextField.delegate = self;
    
    //For active keyboard again
    [yourTextField becomeFirstResponder];
    

    Then implement the textFieldShouldClear delegate

    YourClass.h

        @interface className : UIViewController <UITextFieldDelegate>
    

    YourClass.m

    -(BOOL)textFieldShouldClear:(UITextField *)textField {
        yourTextField.hidden = NO;
        yourTextField.text = @"";
        return YES;
    }
    
    0 讨论(0)
提交回复
热议问题