Skip to content

Commit 33c9590

Browse files
committed
✨ [feat] LinksTextView 추가
1 parent 3b8dffe commit 33c9590

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

Fitfty/Projects/Common/Sources/LinksTextView.swift

+44-1
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,47 @@
66
// Copyright © 2023 Fitfty. All rights reserved.
77
//
88

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

Comments
 (0)