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

后端 未结 10 1512
余生分开走
余生分开走 2020-11-30 00:56

I have subclassed UITextField and implemented the UIKeyInput protocol\'s deleteBackward method to detect backspace being pressed. This works fine on iOS 7 but not on iOS 8.<

10条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 01:33

    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

提交回复
热议问题