问题描述
我正在尝试控制UITextField中的光标位置。用户不能一次插入多个字符到文本字段的中间。它将它移动到文本字段的末尾。所以SO中的帖子:它解决了我的问题。但我需要知道当前光标位置。
I am trying to control the cursor position in the UITextField. Users cannot insert more than one character at a time into the middle of the text field. It moves it to the end of the textfield. So this post in SO: Control cursor position in UITextField It solves my problem. But I need to know the current cursor position.
我的代码如下所示:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField.tag == 201)
{
[myclass selectTextForInput:textField atRange:NSMakeRange(idx, 0)];
}
}
它在idx给我一个错误。我怎么找到?
It is giving me an error at idx. How do I find that?
推荐答案
UITextField
符合 UITextInput
协议,其中包含获取当前选择的方法。但这些方法很复杂。你需要这样的东西:
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)];
}
}
这篇关于在ios中获取UITextField的光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!