Getting the cursor position of UITextField in ios

﹥>﹥吖頭↗ 提交于 2019-12-03 10:34:06

UITextField conforms to the UITextInput protocol which has methods for getting the current selection. But the methods are complicated. You need something like this:

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

Swift version

if let selectedRange = textField.selectedTextRange {

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

My full answer about getting and setting the cursor position is here.

Dimitar K

The code you have posted won't work for determining where the cursor is. You need the get method, not the set. It should be something along the lines of:

- (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
              ...
         }
   }
}

For more information - check the UITextInput protocol http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UITextInput_Protocol/Reference/Reference.html#//apple_ref/occ/intf/UITextInput

Update: @rmaddy has posted some good extra bits I missed in my response - how to handle the text position from the NSTextRange and convert NSTextPosition to int.

Swift Solution.

You can set the cursor padding by subclassing the UITextfield class and implementing these two methods.

Hope it helps someone in need.

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))
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!