有没有机会确定是否在UITextView中点击了空白空间?

问题描述

我在只读模式+手势识别器中使用UITextView使其可编辑以支持URL,并且效果很好,但我遇到了这个问题: 当用户在文本中仅包含URL并点击其下方的空白区域以使UITextView可编辑时,将改为点击URL,然后将用户重定向到该URL。

预期的行为:文本应可编辑。

该问题是由于以下代码而发生的:

extension TextViewController : UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,shouldReceive touch: UITouch) -> Bool {
        if let textView = textView,textView.text.count > 0 {
            var location = touch.location(in: textView)
            location.x -= textView.textContainerInset.left
            location.y -= textView.textContainerInset.top
            let characterIndex = textView.layoutManager.characterIndex(for: location,in: textView.textContainer,fractionOfDistanceBetweenInsertionPoints: nil)
            if (textView.attributedText?.attribute(.link,at: characterIndex,effectiveRange: nil) as? URL) != nil {
                return false
            }
        }
        return true
    }
}

特别是由于“ textView.layoutManager.characterIndex(用于:位置,在:textView.textContainer中,fractionOfDistanceBetweenInsertionPoints:无)”

它将相应的最后一位数字返回给文档:

如果该点下没有字符,则返回最接近的字符

因此,代码的行为就如同点击了URL一样,我看不到任何选项可以检查是否点击了空白空间。 这个想法是检查在点击的位置是否没有URL,然后手势识别器应该收到轻按(在此处返回true) 请提出建议,如果您有任何想法

谢谢!

解决方法

好的,所以我按预期工作了。解决方案是检查点击位置是否在文档的结尾:

if let position = textView.closestPosition(to: location) {
    if position == textView.endOfDocument {
        return true
    }
}

最终代码如下:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,shouldReceive touch: UITouch) -> Bool {
        if let textView = textView,textView.text.count > 0 {
            var location = touch.location(in: textView)
            location.x -= textView.textContainerInset.left
            location.y -= textView.textContainerInset.top
            if let position = textView.closestPosition(to: location) {
                if position == textView.endOfDocument {
                    return true
                }
            }
            
            let characterIndex = textView.layoutManager.characterIndex(for: location,in: textView.textContainer,fractionOfDistanceBetweenInsertionPoints: nil)
            if (textView.attributedText?.attribute(.link,at: characterIndex,effectiveRange: nil) as? URL) != nil {
                return false
            }
        }
        return true
    }

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...