ios - 如何让 UITextField 先全选然后以编程方式编辑?

标签 ios objective-c uitextfield uitextfielddelegate

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

提前致谢。

最佳答案

这可以防止在用户点击所选文本时出现弹出窗口。

要允许第一次点击始终选择所有文本,并让第二次点击取消选择,请将当前代码保留在 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;
}

希望对您有所帮助!

关于ios - 如何让 UITextField 先全选然后以编程方式编辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32805301/

相关文章:

objective-c - NSThread 中的 NSUrlConnection - 没有执行委托(delegate)!

ios - 我们可以在 UITextField 的扩展中调用委托(delegate)吗

iOS 视频文件大小和带宽注意事项

objective-c - 创建包含RestKit库的静态库

ios - 尝试转换为 NSFetchedResultsController "fatal error: unexpectedly found nil while unwrapping an Optional value"?

ios - 在没有 UINavigationBar iOS 标题的后退按钮上添加警报

iOS CPU_FATAL 0% 在后台

objective-c - 为类的所有实例模拟 OCMock 中的方法

swift - 编程 UITextField 在 vi​​ewDidLoad 上不可见

iOS:向下移动 UITextField 的底部边框