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

后端 未结 10 1540
余生分开走
余生分开走 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:46

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
       const char * _char = [string cStringUsingEncoding:NSUTF8StringEncoding];
       int isBackSpace = strcmp(_char, "\b");
    
       if (isBackSpace == -8) {
         NSLog(@"Backspace was pressed");
       }
    
    return YES;
    
    }
    

    Basically this method detects which button you are pressing (or have just pressed). This input comes in as an NSString. We convert this NSString to a C char type and then compare it to the traditional backspace character (\b). Then if this strcmp is equal to -8, we can detect it as a backspace.

提交回复
热议问题