UITextPosition to Int

荒凉一梦 提交于 2019-12-05 05:00:31

the clue is to make a position and then a range with no length and then select it

e.g.

- (IBAction)select:(id)sender {
    //get position: go from end 1 to the left
    UITextPosition *pos = [_textField positionFromPosition:_textField.endOfDocument
                                               inDirection:UITextLayoutDirectionLeft
                                                    offset:1];

    //make a 0 length range at position
    UITextRange *newRange = [_textField textRangeFromPosition:pos
                                                toPosition:pos];

    //select it to move cursor
    _textField.selectedTextRange = newRange;
}
Suragch

Swift 3

I came across this question originally because I was wondering how to convert UITextPosition to an Int (based on your title). So that is what I will answer here. You can get an Int for the current text position like this:

if let selectedRange = textField.selectedTextRange {
    // cursorPosition is an Int
    let cursorPosition = textField.offset(from: textField.beginningOfDocument, to: selectedRange.start)
}

For setting the cursor position and other related tasks, see my fuller answer.

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