繁体   English   中英

如何确定UITextField中删除的位置

[英]How can I determine the location of a deletion in an UITextField

我正在创建一个文本框,允许用户输入日期,并且我想显示所需的格式: mm-dd-yyyy 在键入时,应使用键入的数字替换格式。 例如,如果输入125 ,则应类似于: 12-5d-yyyy

我已经能够做到这一点(使用textField:shouldChangeCharactersInRange:replacementString:方法)。 但是有两个问题:

  1. 当我更新文本字段以使其显示格式以及它们键入的内容时(通过直接设置textField.text ),光标将移至插入文本的末尾。 例如,当前看起来像: 12-30-yyyy| (其中|是光标),但是我希望它看起来像12-30-|yyyy 那么如何将光标放置在它们上次键入的位置?

  2. 如果用户按下Backspace或Delete,我无法确定在哪里发生删除。 我知道只有这样,才能确定他们按退格键或删除是这样的: BOOL thisIsBackspace = ([string length] == 0)其中字符串的值replacementString:但是,这并没有告诉我它发生在哪里。 那么如何确定UITextField中的删除位置呢?

使用UIDatePicker将是解决之道。 除此之外...

在textField:shouldChangeCharactersInRange中:range参数将告诉您实际更改在字段中的何处发生。

您还可以使用stringByReplacingCharactersInRange在编辑后创建字段的值。 然后,您可以使用它进行比较并找到它们的编辑位置。

- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];

    // Now you can compare text and textField.text and find where they are different.

    return YES;
}

您可以使用以下方法放置光标:

[textField setSelectedRange:NSMakeRange(desiredPosition, 0)];

您可以使用方法的“范围”输入来确定删除的位置

textField:shouldChangeCharactersInRange:replacementString:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM