Control cursor position in UITextField

后端 未结 7 2171
你的背包
你的背包 2020-11-29 00:52

I have a UITextField that I\'m forcing formatting on by modifying the text inside the change notification handler. This works great (once I solved the reentranc

7条回答
  •  独厮守ぢ
    2020-11-29 01:12

    Controlling cursor position in a UITextField is complicated because so many abstractions are involved with input boxes and calculating positions. However, it's certainly possible. You can use the member function setSelectedTextRange:

    [input setSelectedTextRange:[input textRangeFromPosition:start toPosition:end]];
    

    Here's a function which takes a range and selects the texts in that range. If you just want to place the cursor at a certain index, just use a range with length 0:

    + (void)selectTextForInput:(UITextField *)input atRange:(NSRange)range {
        UITextPosition *start = [input positionFromPosition:[input beginningOfDocument] 
                                                     offset:range.location];
        UITextPosition *end = [input positionFromPosition:start
                                                   offset:range.length];
        [input setSelectedTextRange:[input textRangeFromPosition:start toPosition:end]];
    }
    

    For example, to place the cursor at idx in the UITextField input:

        [Helpers selectTextForInput:input 
                            atRange:NSMakeRange(idx, 0)];
    

提交回复
热议问题