我有一个连接到平移手势识别器的 UITextView。当我将手指拖到 TextView 上时,我使用 characterIndexForPoint 方法来确定我的手指在哪个字符上,然后突出显示该点的文本。
在某些情况下, View 中的文本有换行符,即使我传入相同的参数,此方法似乎也会返回不同的结果。 touched方法连续调用了两次,一次charIndex是167,然后是270。
我已经检查了 TextView 的 AttributedString,在这两种情况下它的字体大小相同。
- (IBAction)touched:(UIPanGestureRecognizer *)sender {
if (self.txtView.isFirstResponder) {
return;
}
if (sender.state == UIGestureRecognizerStateChanged) {
CGPoint touchPoint = [sender locationInView:self.txtView];
NSUInteger charIndex = [self.txtView.layoutManager
characterIndexForPoint:touchPoint
inTextContainer:self.txtView.textContainer
fractionOfDistanceBetweenInsertionPoints:0];
...
这是一个已知错误吗?我做错了什么吗?
最佳答案
您做错的一件事是 fractionOfDistanceBetweenInsertionPoints:
不应为零。它是一个结果参数,所以它应该是 CGFloat
的地址,或者如果您不关心的话,它应该是 NULL
。
CGPoint touchPoint = [sender locationInView:self.txtView];
CGFloat fraction = 0;
NSUInteger charIndex = [self.txtView.layoutManager
characterIndexForPoint:touchPoint
inTextContainer:self.txtView.textContainer
fractionOfDistanceBetweenInsertionPoints:&fraction];
稍后您可能对 fractionOfDistanceBetweenInsertionPoints:
不感兴趣,但它可能会帮助您诊断此问题。您传递的点可能不明确,它会帮助您看清这一点。
关于objective-c - characterIndexForPoint 为相同的参数返回不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19743329/