是否有机会确定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(用于:location,在:textView.textContainer中,插入点之间的距离分数:nil(">

它相应地返回文档的最后一个数字:

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

因此,代码的行为就像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
}

最新更新