How can I accurately detect if a link is clicked inside UILabels in Swift 4?

后端 未结 6 1063
暗喜
暗喜 2021-02-07 12:24

Edit

See my answer for a full working solution:

I managed to solve this myself by using a UITextView instead of a UILabel

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-07 12:41

    For Dan Bray's solution above to work for me I had to call super.hitTest(point, with:event) instead of returning nil. Otherwise touchesBegan and touchesEnded were not invoked. I use the textViews inside a UIScrollView.

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        var location = point
        location.x -= self.textContainerInset.left
        location.y -= self.textContainerInset.top
        if location.x > 0 && location.y > 0 {
    
    
        let index = self.layoutManager.characterIndex(for: location, in: self.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
            for textLink in textLinks {
                let range = ((text ?? "") as NSString).range(of: textLink.0)
                if NSLocationInRange(index, range) {
                    callback = {
                        self.linkDelegate?.didTap(text: textLink.0, withLink: textLink.1, inTextView: self)
                    }
                    return self
                }
            }
        }
        callback = nil
        return super.hitTest(point, with:event)
    }
    

提交回复
热议问题