【问题标题】:Trying to delete a character within a string in a UITextField using backspace尝试使用退格键删除 UITextField 中字符串中的字符
【发布时间】:2014-08-07 16:44:27
【问题描述】:

我的应用程序中有一个 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 对象,但我不确定在这种情况下如何使用。有什么想法吗?

【问题讨论】:

  • NSMakeRange(stringName.length - 1, stringName.length); ?

标签: objective-c nsstring uitextfielddelegate nsrange


【解决方案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;
}

【讨论】:

  • 非常感谢您的解决方案。它几乎可以工作,但我唯一的问题是光标总是返回到行尾而不是删除字符所在的位置。有什么建议吗?
  • 问得好,我认为post 有你需要的东西。如果没有,请告诉我,我会进一步深入研究。
  • 我已经更新了上面的代码,向您展示了我所拥有的。我至少能够删除行内的空格,但不能删除任何字符。我只能从行尾删除字符。再次感谢您的所有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-21
  • 1970-01-01
相关资源
最近更新 更多