• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 替换文本时更正 UITextField 中的文本光标

[复制链接]
菜鸟教程小白 发表于 2022-12-12 21:13:32 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在为输入到 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap