在ios中获取UITextField的光标位置

时间:2013-05-08 03:54:46

标签: ios uitextfield

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

我的代码如下所示:

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

在idx上给我一个错误。我怎么找到它?

4 个答案:

答案 0 :(得分:27)

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

- (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)];
    }
}

答案 1 :(得分:5)

Swift版本

if let selectedRange = textField.selectedTextRange {

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

关于获取和设置光标位置的完整答案是here

答案 2 :(得分:3)

您发布的代码无法确定光标的位置。你需要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。

答案 3 :(得分:0)

快速解决方案。

可以通过子类化UITextfield类并实现这两个方法来设置光标填充。

希望它可以帮助有需要的人。

override func textRect(forBounds bounds: CGRect) -> CGRect {
    return bounds.inset(by: UIEdgeInsets.init(top: 4, left: 40, bottom: 1, right: 15))
}

override func editingRect(forBounds bounds: CGRect) -> CGRect {
    return bounds.inset(by: UIEdgeInsets.init(top: 4, left: 40, bottom: 1, right: 15))
}