From 18f8f7d9f37fdc73bd9aa7bfbb9f561691de5c4b Mon Sep 17 00:00:00 2001 From: "Christiano, Kevin" Date: Thu, 2 May 2019 15:37:12 -0400 Subject: [PATCH] Two means to set actionable text in code. --- MVMCoreUI/Atoms/Views/Label.swift | 36 +++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/MVMCoreUI/Atoms/Views/Label.swift b/MVMCoreUI/Atoms/Views/Label.swift index 793b8aa5..d6f0a5ed 100644 --- a/MVMCoreUI/Atoms/Views/Label.swift +++ b/MVMCoreUI/Atoms/Views/Label.swift @@ -46,6 +46,8 @@ public typealias ActionBlock = () -> Void private var clauses: [ActionableClause] = [] + var didSetGestureRecognizer = false + // Used for tappable links in the text. private struct ActionableClause { var labelView: Label? @@ -53,11 +55,7 @@ public typealias ActionBlock = () -> Void var length: Int? var actionText: String? var actionBlock: ActionBlock? - - var words: [String]? { - return actionText?.components(separatedBy: " ") - } - + var range: NSRange { return NSRange(location: location ?? 0, length: length ?? 0) } @@ -184,6 +182,31 @@ public typealias ActionBlock = () -> Void Label.setGestureInteraction(for: self) } + /** + Provides an actionable range of text. + + Allows actionable range to be established by a particular substring of the containing label text. + + - Attention: This method expects text to be set first. Otherwise, it will do nothing. + - Parameters: + - actionText: The actionable text contained witin the label's text. + - actionBlock: The code triggered when tapping the range of text. + */ + @objc public func addTappableLinkAttribute(actionText: String, actionBlock: @escaping ActionBlock) { + + guard let text = self.text else { return } + let string = text as NSString + let range = string.range(of: actionText) + + clauses.append(ActionableClause(labelView: self, + location: range.location, + length: range.length, + actionText: actionText, + actionBlock: actionBlock)) + + Label.setGestureInteraction(for: self) + } + /** Makes the view interactive and applies the gesture recognizer. @@ -192,8 +215,9 @@ public typealias ActionBlock = () -> Void */ private static func setGestureInteraction(for label: Label) { - if !label.isUserInteractionEnabled { + if !label.didSetGestureRecognizer { label.isUserInteractionEnabled = true + label.didSetGestureRecognizer = true let tapGesture = UITapGestureRecognizer(target: label, action: #selector(textLinkTapped(_:))) tapGesture.numberOfTapsRequired = 1 label.addGestureRecognizer(tapGesture)