Ios 是否有机会确定UITextView中是否有空闲空间?
我在只读模式+手势识别器中使用UITextView使其可编辑以支持URL,它工作得很好,但我遇到了一个问题: 当用户在文本中只有URL,并点击其下方的空白以使UITextView可编辑时,会点击URL,用户会被重定向到URL 预期行为:文本应可编辑 出现此问题的原因是以下代码:Ios 是否有机会确定UITextView中是否有空闲空间?,ios,swift,url,uitextview,Ios,Swift,Url,Uitextview,我在只读模式+手势识别器中使用UITextView使其可编辑以支持URL,它工作得很好,但我遇到了一个问题: 当用户在文本中只有URL,并点击其下方的空白以使UITextView可编辑时,会点击URL,用户会被重定向到URL 预期行为:文本应可编辑 出现此问题的原因是以下代码: extension TextViewController : UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: U
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中,插入点之间的距离分数: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
}