附加到stringByReplacingCharactersInRange的最后一个字母

时间:2013-01-19 01:21:14

标签: objective-c xcode cocoa-touch

我有UItextfield根据预定义的字符串自动完成其值。如果第一个字符串currentString中有多个单词,则结果显示的最后一个字符currentString附加到其中。

所以在示例代码中

在输入No时,UITextField生成的文字变为Note todayt(第二个字的最后一个字母附加到字符串)

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

NSString *currentString = [_txt.text stringByReplacingCharactersInRange:range withString:string];


 NSString *currentString = [_txt.text stringByReplacingCharactersInRange:range withString:string];
if ([currentString isEqualToString:@"No t"]) {
    textField.text = @"Note today";

有没有办法可以避免这种行为?

我试过了

 if(_txt.text.length>1)
    {
       _txt.text =[textField.text substringToIndex:[textField.text length] - 1];

    }

if(_txt.text.length>1)
    {
        NSString *text2;

        NSString *currentString = textField.text;
        NSString *newString = [text2 substringToIndex:[text2 length]-1];
        textField.text=newString;
    }

    return NO;
}
return YES;

}

2 个答案:

答案 0 :(得分:2)

我愿意打赌你返回YES,导致“t”被输入。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range  replacementString:(NSString *)string {
  NSString *currentString = [_txt.text stringByReplacingCharactersInRange:range withString:string];

  if ([currentString isEqualToString:@"No t"]) {
    textField.text = @"Note today";
    return NO;
  }

  return YES;
}

答案 1 :(得分:0)

好的排序了,我添加了一个if语句来删除额外的字符

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

NSString *currentString = [_txt.text stringByReplacingCharactersInRange:range  withString:string];


NSString *currentString = [_txt.text stringByReplacingCharactersInRange:range withString:string];
if ([currentString isEqualToString:@"No t"]) {
textField.text = @"Note today";

  }


 if(_txt.text.length>=4)

  {
        NSString *text;

        text =[[textField text] stringByAppendingString:string];
        NSString *newString = [text substringToIndex:[text length]-1];

        textField.text=newString;


    return NO;

   }
   return YES;
}