ios UITextField 设置光标开始文本位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15931227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:08:34  来源:igfitidea点击:

UITextField set cursor to start text position

iosobjective-cuitextfield

提问by RomanS

I need to move cursor to start text position on set focus on the textfield. Is it possible tot do?

我需要移动光标以在文本字段上设置焦点时开始文本位置。有可能吗?

回答by omz

Set your view controller (or some other appropriate object) as the text field's delegateand implement the textFieldDidBeginEditing:method like this:

将您的视图控制器(或其他一些适当的对象)设置为文本字段delegate并实现如下textFieldDidBeginEditing:方法:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    UITextPosition *beginning = [textField beginningOfDocument];
    [textField setSelectedTextRange:[textField textRangeFromPosition:beginning
                                                          toPosition:beginning]];
}

Note that setSelectedTextRange:is a protocol method of UITextInput(which UITextFieldimplements), so you won't find it directly in the UITextFielddocumentation.

请注意,这setSelectedTextRange:UITextInputUITextField实现)的协议方法,因此您不会直接在UITextField文档中找到它。

回答by Anoop Vaidya

self.selectedTextRange = [self textRangeFromPosition:newPos toPosition:newPos];

Check this Finding the cursor position in a UITextField

检查这个在 UITextField 中查找光标位置

回答by Dave G

If anyone's looking for the answer in Swift:

如果有人在 Swift 中寻找答案:

let desiredPosition = textField.beginningOfDocument
textField.selectedTextRange = textField.textRangeFromPosition(desiredPosition, toPosition: desiredPosition)

But I believe this only works if the cursor is already in the text field. You can use this to do that:

但我相信这只适用于光标已经在文本字段中的情况。你可以用它来做到这一点:

textField.becomeFirstResponder()
let desiredPosition = textField.beginningOfDocument
textField.selectedTextRange = textField.textRangeFromPosition(desiredPosition, toPosition: desiredPosition)