我有一個文本框,&使用shouldChangeCharactersInRange
方法來獲取值。NSRange`replaceCharactersInRange`在退格和輸入新字符後崩潰的應用程序
這裏是我的代碼:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSLog(@"Pressing : %@\n", string);
NSMutableString *text = [NSMutableString stringWithString:textField.text];
NSLog(@"length: %lu", (unsigned long)range.length);
NSLog(@"location: %lu\n", (unsigned long)range.location);
NSLog(@"before text: %@", textField.text);
[text replaceCharactersInRange:range withString:string];
NSLog(@"After replacement , Text: %@\n\n", text);
// My work..
return YES;
}
我先加字符 'T' 到文本框,它工作正常..
2016-03-02 10:06:23.162 MyTextFieldApp[12006:4323645] Pressing : T
2016-03-02 10:06:23.163 MyTextFieldApp[12006:4323645] length: 0
2016-03-02 10:06:23.163 MyTextFieldApp[12006:4323645] location: 0
2016-03-02 10:06:23.163 MyTextFieldApp[12006:4323645] before text:
2016-03-02 10:06:23.163 MyTextFieldApp[12006:4323645] After replacement , Text: T
然後,我就退格刪除字符,這也適用很好..
2016-03-02 10:06:30.979 MyTextFieldApp[12006:4323645] Pressing :
2016-03-02 10:06:30.980 MyTextFieldApp[12006:4323645] length: 1
2016-03-02 10:06:30.980 MyTextFieldApp[12006:4323645] location: 0
2016-03-02 10:06:30.980 MyTextFieldApp[12006:4323645] before text: T
2016-03-02 10:06:30.981 MyTextFieldApp[12006:4323645] After replacement , Text:
但是,當我要添加新字符,然後,它崩潰在replaceString ..
注意:此時間,範圍給出長度爲0 &位置1,而第一次也當我加入噸至空文本框,它給出一個長度爲0以及位置0
2016-03-02 10:07:02.158 MyTextFieldApp[12006:4323645] Pressing : T
2016-03-02 10:07:02.158 MyTextFieldApp[12006:4323645] length: 0
2016-03-02 10:07:02.159 MyTextFieldApp[12006:4323645] location: 1
2016-03-02 10:07:02.159 MyTextFieldApp[12006:4323645] before text:
2016-03-02 10:07:02.159 MyTextFieldApp[12006:4323645] *** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString replaceCharactersInRange:withString:]: Range or index out of bounds'
我無法檢測到問題在哪裏?
你明白嗎,爲什麼我要獲得位置1?這是我沒有得到.. – Simmy
我不知道,你的程序或其他東西是錯誤的字段中鍵入。我寫了完全相同的程序,只是爲了明智地檢查UITextField是否做得正確,並且從我的輸出中可以看到,我得到的範圍都很好。 – par