控制UITextField中的光标位置 [英] Control cursor position in UITextField
问题描述
我有一个 UITextField
我正在通过修改更改通知处理程序中的文本来强制格式化。这很有效(一旦我解决了重入问题),但又给我留下了一个棘手的问题。
如果用户将光标移动到字符串末尾以外的某个位置,则我的格式更改会将其移动到字符串的末尾。这意味着用户不能一次插入多个字符到文本字段的中间。
有没有办法记住然后重置 UITextField
中的光标位置?
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 reentrancy issues) but leaves me with one more nagging problem.
If the user moves the cursor someplace other than the end of the string then my formatting change moves it to the end of the string. This means users cannot insert more than one character at a time into the middle of the text field.
Is there a way to remember and then reset the cursor position in the UITextField
?
推荐答案
控制UITextField中的光标位置很复杂,因为输入框和计算位置涉及很多抽象。但是,这当然是可能的。您可以使用成员函数 setSelectedTextRange
:
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]];
这是一个函数,它取一个范围并选择该范围内的文本。如果您只想将光标放在某个索引处,只需使用长度为0的范围:
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]];
}
例如,将光标放在 idx
在UITextField 输入
:
For example, to place the cursor at idx
in the UITextField input
:
[Helpers selectTextForInput:input
atRange:NSMakeRange(idx, 0)];
这篇关于控制UITextField中的光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!