Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 8 additions & 11 deletions ClickableLabel/InteractiveLinkLabel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,13 @@ class InteractiveLinkLabel: UILabel {

func configure() {
isUserInteractionEnabled = true
addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(labelTapped)))
}

override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let superBool = super.point(inside: point, with: event)
@objc private func labelTapped(_ recognizer: UITapGestureRecognizer) {

guard let attributedText = attributedText else { return }

// Configure NSTextContainer
let textContainer = NSTextContainer(size: bounds.size)
textContainer.lineFragmentPadding = 0.0
Expand All @@ -38,15 +39,13 @@ class InteractiveLinkLabel: UILabel {
let layoutManager = NSLayoutManager()
layoutManager.addTextContainer(textContainer)

guard let attributedText = attributedText else {return false}

// Configure NSTextStorage and apply the layout manager
let textStorage = NSTextStorage(attributedString: attributedText)
textStorage.addAttribute(NSAttributedString.Key.font, value: font!, range: NSMakeRange(0, attributedText.length))
textStorage.addLayoutManager(layoutManager)

// get the tapped character location
let locationOfTouchInLabel = point
let locationOfTouchInLabel = recognizer.location(in: self)

// account for text alignment and insets
let textBoundingBox = layoutManager.usedRect(for: textContainer)
Expand Down Expand Up @@ -74,7 +73,7 @@ class InteractiveLinkLabel: UILabel {
let rightMostPointInLineTapped = CGPoint(x: bounds.size.width, y: font.lineHeight * CGFloat(lineTapped))
let charsInLineTapped = layoutManager.characterIndex(for: rightMostPointInLineTapped, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)

guard characterIndex < charsInLineTapped else {return false}
guard characterIndex < charsInLineTapped else { return }

let attributeName = NSAttributedString.Key.link

Expand All @@ -85,8 +84,6 @@ class InteractiveLinkLabel: UILabel {
UIApplication.shared.open(url)
}
}

return superBool

}

}