我有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;
}
答案 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;
}