在ios中获取UITextField的游标位置

我试图控制UITextField中的光标位置。 用户不能一次插入多个字符到文本字段的中间。 它将其移动到文本字段的末尾。 所以这个post在SO: 控制UITextField中的光标位置它解决了我的问题。 但是我需要知道当前的光标位置。

我的代码如下所示:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (textField.tag == 201) { [myclass selectTextForInput:textField atRange:NSMakeRange(idx, 0)]; } } 

这是给我一个错误在idx。 我如何find?

UITextField符合UITextInput协议,该协议有获取当前select的方法。 但方法很复杂。 你需要这样的东西:

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (textField.tag == 201) { UITextRange *selRange = textField.selectedTextRange; UITextPosition *selStartPos = selRange.start; NSInteger idx = [textField offsetFromPosition:textField.beginningOfDocument toPosition:selStartPos]; [myclass selectTextForInput:textField atRange:NSMakeRange(idx, 0)]; } } 

Swift版本

 if let selectedRange = textField.selectedTextRange { let cursorPosition = textField.offsetFromPosition(textField.beginningOfDocument, toPosition: selectedRange.start) print("\(cursorPosition)") } 

关于获取和设置光标位置的完整答案在这里 。

您发布的代码将无法确定游标在哪里。 你需要get方法,而不是set。 应该是这样的:

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (textField.tag == 201) { UITextRange selectedRange = [textField selectedTextRange]; // here you will have to check whether the user has actually selected something if (selectedRange.empty) { // Cursor is at selectedRange.start ... } else { // You have not specified home to handle the situation where the user has selected some text, but you can use the selected range and the textField selectionAffinity to assume cursor is on the left edge of the selected range or the other ... } } } 

有关更多信息,请查看UITextInput协议http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UITextInput_Protocol/Reference/Reference.html#//apple_ref/occ/intf/UITextInput

更新:@rmaddy发布了一些额外的好处,我错过了我的回应 – 如何处理NSTextRange的文本位置,并将NSTextPosition转换为int。