OGeek|极客世界-中国程序员成长平台

标题: ios - 替换文本时更正 UITextField 中的文本光标 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 21:13
标题: ios - 替换文本时更正 UITextField 中的文本光标

我正在为输入到 UITextField 中的文本实现快捷方式替换。

例如,如果文本字段已经包含“a”并且他在其后键入另一个“a”,我会将其替换为“ä”。在另一种情况下,如果他键入“a”,然后键入“b”,我会将其替换为“XYZ”。如果文本包含两个连续的空格,我喜欢用一个空格替换它们。

因此,根据用户键入的内容,我可能会将其替换为更长、更短或相同长度的文本。

简单的方法是实现 [UITextFieldDelegate textField: shouldChangeCharactersInRange: ... 委托(delegate)函数,将替换文本分配给 textField.text ,并返回NO。

但这也需要相应地调整光标位置,这就是我正在努力解决的问题。

我目前正在“手动”处理此光标定位。这有点难看,所以我想知道是否有更优雅的解决方案。毕竟,更换文本后处理光标位置的所有代码(例如,选择,然后粘贴时)已在 uitextfield 代码中实现。我只是想知道是否有更多它是为了满足我的需求而暴露出来的,而我还没有找到它。



Best Answer-推荐答案


我真的认为您不需要 textField:shouldChangeCharactersInRange:replacementString:。有一种简单的方法可以解决您的要求,并且该解决方案不会出现光标问题。

您应该在 viewDidLoad 中添加这行代码(self.textField 是您的 UITextField):

[[NSNotificationCenter defaultCenter] addObserver:self selectorselector(shortcut name:UITextFieldTextDidChangeNotification object:self.textField];

然后,您应该添加选择器,例如:

- (void) shortcut: (NSNotification*) notification
{
    UITextField *notificationTextField = [notification object];

    if (notificationTextField == self.textField)
    {
        [self checkDoubleA:notificationTextField];
        [self checkDoubleAB:notificationTextField];
        [self checkDoubleSpace:notificationTextField];
    }
}

那么你只需要添加3个方法来检查你的快捷方式:

-(void) checkDoubleA: (UITextField*) textField
{
    NSMutableString *string =  [textField.text mutableCopy];
    NSRange range = [string rangeOfString"aa"];
    if (range.location == NSNotFound)
    {
        NSLog(@"string was not found");
    }
    else
    {
        [string replaceCharactersInRange:range withString"ä"];
    }
    textField.text = string;
}

-(void) checkDoubleAB: (UITextField*) textField
{
    NSMutableString *string =  [textField.text mutableCopy];
    NSRange range = [string rangeOfString"ab"];
    if (range.location == NSNotFound)
    {
        NSLog(@"string was not found");
    }
    else
    {
        [string replaceCharactersInRange:range withString"XYZ"];
    }
    textField.text = string;
}

- (void) checkDoubleSpace: (UITextField*) textField
{
    NSMutableString *string =  [textField.text mutableCopy];
    NSRange range = [string rangeOfString"  "];
    if (range.location == NSNotFound)
    {
        NSLog(@"String was not found");
    }
    else
    {
        [string replaceCharactersInRange:range withString" "];
    }
    textField.text = string;
}

您可以下载此代码的演示 here .

关于ios - 替换文本时更正 UITextField 中的文本光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22886361/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4