问题描述
我正在尝试确定,已经点击了 UITextView
中的哪个特定字符。我尝试使用 characterRangeAtPoint:
方法。但它始终返回nil,无论在 UITextView
中我点击。
我甚至编写并运行以下代码:
I'm trying to determine, which particular character in UITextView
has been tapped. I tried to use characterRangeAtPoint:
method. But it always returns nil, wherever in the UITextView
I tap.I even wrote and run the following piece of code:
for (int x = 0; x<1000; x++) {
pos.x = x;
for (int y = 0; y<1000; y++) {
pos.y = y;
UITextRange * range = [textView characterRangeAtPoint:pos];
if (range!=nil) {
NSLog(@"x: %f, y: %f", pos.x, pos.y);
}
}
}
好吧,它永远不会到达 NSLog
字符串。
我做错了什么?
Well, it never reaches the NSLog
string.What am I doing wrong?
推荐答案
这是iOS 7的错误。 characterRangeAtPoint:
总是返回 nil
,除非事先至少选择过一次文本。
This is an iOS 7 bug. characterRangeAtPoint:
always returns nil
, unless some text has been selected at least once beforehand.
作为解决方法,您可以事先调用 setSelectedRange:
或 setSelectedTextRange:
,但随后 textView
会突出显示您的选择。我提出了以下解决方案:
As a workaround, you could call setSelectedRange:
or setSelectedTextRange:
beforehand, but then the textView
would highlight your selection. I came up with the following solution:
[textView select:textView];
[textView setSelectedTextRange:nil];
调用这两种方法后, characterRangeAtPoint:
将按预期开始工作。
After you call these two methods, characterRangeAtPoint:
will start working as expected.
请注意,在初始化 textView
之后,您只需要调用一次。
Note that you just need to call this once after textView
has been initialized.
编辑:我的答案是从编辑的,除非事先选择了一些文字到除非当前选择了某些文字。这是错误的:当前不需要选择文本,只需选择一次。随后对 setSelectedRange:
的所有后续调用都将成功,如我的说明中所述。为了进一步明确而进行了编辑。
my answer was edited from "unless some text has been selected beforehand" to "unless some text is currently selected". This is wrong: text doesn't need to be currently selected, it just has to be selected once. All subsequent calls to setSelectedRange:
will then be successful, as stated in my note. Edited back for further clarity.
这篇关于检测轻拍的角色。 UITextView characterRangeAtPoint始终返回nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!