|
6 | 6 | // Copyright © 2023 Fitfty. All rights reserved.
|
7 | 7 | //
|
8 | 8 |
|
9 |
| -import Foundation |
| 9 | +import UIKit |
| 10 | + |
| 11 | +public final class LinksTextView: UITextView, UITextViewDelegate { |
| 12 | + public typealias Links = [String: String] |
| 13 | + public typealias OnLinkTap = (URL) -> Bool |
| 14 | + |
| 15 | + public var onLinkTap: OnLinkTap? |
| 16 | + |
| 17 | + override init(frame: CGRect, textContainer: NSTextContainer?) { |
| 18 | + super.init(frame: frame, textContainer: textContainer) |
| 19 | + isEditable = false |
| 20 | + isSelectable = true |
| 21 | + isScrollEnabled = false |
| 22 | + delegate = self |
| 23 | + } |
| 24 | + |
| 25 | + required init?(coder: NSCoder) { |
| 26 | + super.init(coder: coder) |
| 27 | + } |
| 28 | + |
| 29 | + public func addLinks(_ links: Links) { |
| 30 | + guard attributedText.length > 0 else { |
| 31 | + return |
| 32 | + } |
| 33 | + let mText = NSMutableAttributedString(attributedString: attributedText) |
| 34 | + |
| 35 | + for (linkText, urlString) in links { |
| 36 | + if linkText.count > 0 { |
| 37 | + let linkRange = mText.mutableString.range(of: linkText) |
| 38 | + mText.addAttribute(.link, value: urlString, range: linkRange) |
| 39 | + mText.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: linkRange) |
| 40 | + } |
| 41 | + } |
| 42 | + attributedText = mText |
| 43 | + } |
| 44 | + |
| 45 | + public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool { |
| 46 | + return onLinkTap?(URL) ?? true |
| 47 | + } |
| 48 | + |
| 49 | + public func textViewDidChangeSelection(_ textView: UITextView) { |
| 50 | + textView.selectedTextRange = nil |
| 51 | + } |
| 52 | +} |
0 commit comments