我的应用程序中有一个UITextField,我允许用户输入和删除文本。我正在实现UITextFieldDelegate方法:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{ }
在这个方法中,我做了一些事情(与这个问题无关),然后调用另一个方法:
-(NSString*) formatString:(NSString*) stringName stringRange:(NSRange)range deleteLastChar:(BOOL)deleteLastChar {
...
NSString *newString = [stringName mutableCopy];
if(deleteLastChar) {
//this line below is only deleting spaces within the text, but not deleting any characters. I am unable to position the cursor in front of any character within the line itself, but only at the end of the line. I am only able to delete characters from the end of the end of the line, but not from within the line.
[newString delecteCharactersInRange:NSMakeRange(range.location, 1)];
}
return newString;
}
在这种方法中,我试图使用键盘的退格键(标准功能)删除光标旁边的字符。在这种情况下,“stringName”是在textField中输入的整个字符串。相反,我总是删除整个字符串的最后一个字符。我意识到我需要使用NSRange对象,但我不确定在这种情况下如何。有什么想法吗?
答案 0 :(得分:1)
这是一种使用UITextField
而不仅仅是字符串
-(void)RemoveCharacter{
// Reference UITextField
UITextField *myField = _inputField;
UITextRange *myRange = myField.selectedTextRange;
UITextPosition *myPosition = myRange.start;
NSInteger idx = [myField offsetFromPosition:myField.beginningOfDocument toPosition:myPosition];
NSMutableString *newString = [myField.text mutableCopy];
// Delete character before index location
[newString deleteCharactersInRange:NSMakeRange(--idx, 1)];
// Write the string back to the UITextField
myField.text = newString;
}