如何先制作 UITextField select 然后以编程方式编辑?

How to make UITextField select all first and then edit programatically?

我有一个UITextField。第一次单击时,我想以编程方式 select all 文本。所以我在 textFieldDidBeginEditing: 委托方法中调用了 [textField selectAll:nil] 。当我进行下一次点击时,我希望它成为正常的编辑模式。如何以编程方式实现它?

提前致谢。

这可以防止在用户点击 selected 文本时出现弹出框。

要允许第一次点击始终 select 所有文本,并让第二次点击 deselect,请将当前代码保留在 textFieldDidBeginEditing 方法中,并扩展 UITextField 覆盖 canPerformAction:withSender:,以防止弹出窗口出现,如下所示:

UITextField 子类

- (BOOL) canPerformAction:(SEL)action withSender:(id)sender {
    /* Prevent action popovers from showing up */

    if (action == @selector(paste:)
        || action == @selector(cut:)
        || action == @selector(copy:)
        || action == @selector(select:)
        || action == @selector(selectAll:)
        || action == @selector(delete:)
        || action == @selector(_define:)
        || action == @selector(_promptForReplace:)
        || action == @selector(_share:) )
    {
        //Get the current selection range
        UITextRange *selectedRange = [self selectedTextRange];

        //Range with cursor at the end, and selecting nothing
        UITextRange *newRange = [self textRangeFromPosition:selectedRange.end toPosition:selectedRange.end];

        //Set the new range
        [self setSelectedTextRange:newRange];

        return NO;
    } else {
        //Handle other actions?
    }

    return [super canPerformAction:action withSender:sender];
}

UITextFieldDelegate 方法

//Select the text when text field receives focus
- (void) textFieldDidBeginEditing:(UITextField *)textField
{
    [textField selectAll:nil];
}

//Hide the keyboard when the keyboard "Done" button is pressed
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];

    return TRUE;
}

希望对您有所帮助!