iOS小问题之 tableviewCell嵌套TextView,
2017-09-10 本文已影响225人
盛夏凉风
在tableviewCell嵌套TextView,一般在评论功能里用的很多,例如微博。

这里有个问题,里面一些蓝色的地方需要响应点击,而点击整个cell也需要响应点击事件,其中被TextView捕获到之后,cell的点击事件就不被响应了。
这里我们需要点击蓝色部分响应TextView点击事件,点其他部分,响应cell点击事件
这里我们可以重写一下TextView的点击事件
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
var location = point
location.x -= self.textContainerInset.left
location.y -= self.textContainerInset.top
// find the character that's been tapped
let characterIndex = self.layoutManager.characterIndex(for: location, in: self.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
if characterIndex < self.textStorage.length {
// if the character is a link, handle the tap as UITextView normally would
if (self.textStorage.attribute(NSLinkAttributeName, at: characterIndex, effectiveRange: nil) != nil) {
return self
}
}
// otherwise return nil so the tap goes on to the next receiver
return nil
}
解决了,意思就是如果点击Textview没有url的时候,将点击事件传到下一层,这样的话,点击非蓝色部分,cell也可以响应点击事件了。