UItextfield shouldChangeCharactersInRange方法backSpace不起作用

时间:2014-12-06 06:43:22

标签: ios objective-c ios8 uitextfield uitextfielddelegate

我实现了这段代码,但是在我按下UITextfield中的删除按钮之前,退格键无法正常工作 我想用Backspace删除。

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

    NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:_demo_str];
    for (int i = 0; i < [string length]; i++) {
         unichar c = [string characterAtIndex:i];
         if ([myCharSet characterIsMember:c]) {
            return YES;
      }
    }
    return NO;
  }

2 个答案:

答案 0 :(得分:0)

试试这段代码。这对我有用

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

  NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:_demo_str];
  for (int i = 0; i < [string length]; i++) {
     unichar c = [string characterAtIndex:i];
     if ([myCharSet characterIsMember:c]) {
        return YES;
     }
     else
     {
         return NO;
     }
  }
   return YES;
}

答案 1 :(得分:-1)

use this code

NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString: _demo_str];
if(range.length > 0){

    if( !string || [string isEqualToString:@""] || string.length == 0){
          return YES;
    }
    else{
        for (int i = 0; i < [string length]; i++) {
            unichar c = [string characterAtIndex:i];
            if ([myCharSet characterIsMember:c]) {
                return YES;
            }
        }
    }

     return NO;
}
else{
    for (int i = 0; i < [string length]; i++) {
        unichar c = [string characterAtIndex:i];
        if ([myCharSet characterIsMember:c]) {
            return YES;
        }
    }
      return NO;
}