问题
I need to move cursor to start text position on set focus on the textfield. Is it possible tot do?
回答1:
Set your view controller (or some other appropriate object) as the text field's delegate
and implement the textFieldDidBeginEditing:
method like this:
- (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 UITextField
implements), so you won't find it directly in the UITextField
documentation.
回答2:
self.selectedTextRange = [self textRangeFromPosition:newPos toPosition:newPos];
Check this Finding the cursor position in a UITextField
回答3:
If anyone's looking for the answer in 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)
来源:https://stackoverflow.com/questions/15931227/uitextfield-set-cursor-to-start-text-position