首页 文章

如何确定UITextField中删除的位置

提问于
浏览
0

我正在创建一个允许用户输入日期的文本字段,我想显示所需的格式: mm-dd-yyyy . 在键入时,它应该用他们键入的数字替换格式 . 例如,如果他们输入 125 ,它应该如下所示: 12-5d-yyyy .

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

  • 当我更新文本字段以便显示格式加上他们键入的内容时(通过直接设置 textField.text ),光标将转到插入文本的末尾 . 例如,它目前看起来像: 12-30-yyyy| (其中 | 是光标),但我希望它看起来像 12-30-|yyyy . So how can I place the cursor where they last typed?

  • 如果用户按退格键或删除,我无法确定删除的位置 . 我知道确定他们按下退格键或删除的唯一方法是这样的: BOOL thisIsBackspace = ([string length] == 0) (其中string是 replacementString: 的值 . 但这并不能告诉我它出现在哪里. So how can I determine where a deletion occurs in UITextField?

2 回答

  • 0

    使用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;
    }
    
  • 1

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

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

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

    textField:shouldChangeCharactersInRange:replacementString:
    

相关问题