检测点击的字符.UITextView characterRangeAtPoint始终返回nil

ill*_*yge 5 iphone objective-c uikit core-text ios

我正在试图确定,哪个特定字符UITextView已被挖掘.我试着用characterRangeAtPoint:方法.但它总是会返回零,无论UITextView我在哪里点击.我甚至编写并运行以下代码:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

好吧,它永远不会到达NSLog字符串.我究竟做错了什么?

Iva*_*chi 8

这是iOS 7的错误.characterRangeAtPoint:总是返回nil,除非事先至少选择过一次文本.

作为一种解决方法,您可以打电话setSelectedRange:setSelectedTextRange:事先,但随后textView会突出显示您的选择.我提出了以下解决方案:

[textView select:textView];
[textView setSelectedTextRange:nil];
Run Code Online (Sandbox Code Playgroud)

调用这两种方法后,characterRangeAtPoint:将按预期开始工作.

请注意,您只需textView在初始化后调用一次.

编辑:我的回答是从编辑"除非一些文字已预先选择了""除非一些文本当前选择".这是错误的:当前不需要选择文本,只需选择一次.setSelectedRange:如我的说明所述,随后的所有电话都会成功.编辑回来进一步澄清.


Tal*_*tle 5

您的UITextView必须是可选择的.在故事板中,选中"可选"复选框.

在代码中,

textView.selectable = YES;
Run Code Online (Sandbox Code Playgroud)

这也是-closestPositionToPoint:UITextView上的方法所必需的.