forked from gonzalezreal/AttributedText
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAttributedTextImpl+tvOS.swift
84 lines (71 loc) · 2.21 KB
/
AttributedTextImpl+tvOS.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#if os(tvOS)
import SwiftUI
extension AttributedTextImpl: UIViewRepresentable {
func makeUIView(context: Context) -> TextView {
let uiView = TextView()
uiView.backgroundColor = .clear
uiView.textContainerInset = .zero
uiView.isScrollEnabled = false
uiView.textContainer.lineFragmentPadding = 0
uiView.delegate = context.coordinator
return uiView
}
func updateUIView(_ uiView: TextView, context: Context) {
uiView.attributedText = attributedText
uiView.maxLayoutWidth = maxLayoutWidth
uiView.textContainer.maximumNumberOfLines = context.environment.lineLimit ?? 0
uiView.textContainer.lineBreakMode = NSLineBreakMode(
truncationMode: context.environment.truncationMode
)
context.coordinator.openLink = onOpenLink ?? { context.environment.openURL($0) }
textSizeViewModel.didUpdateTextView(uiView)
}
func makeCoordinator() -> Coordinator {
Coordinator()
}
}
extension AttributedTextImpl {
final class TextView: UITextView {
var maxLayoutWidth: CGFloat = 0 {
didSet {
guard maxLayoutWidth != oldValue else { return }
invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
guard maxLayoutWidth > 0 else {
return super.intrinsicContentSize
}
return sizeThatFits(CGSize(width: maxLayoutWidth, height: .greatestFiniteMagnitude))
}
}
final class Coordinator: NSObject, UITextViewDelegate {
var openLink: ((URL) -> Void)?
func textView(
_: UITextView,
shouldInteractWith URL: URL,
in _: NSRange,
interaction: UITextItemInteraction
) -> Bool {
guard case .invokeDefaultAction = interaction else {
return false
}
if let openLink = self.openLink {
openLink(URL)
return false
} else {
return true
}
}
func textView(
_: UITextView,
shouldInteractWith _: NSTextAttachment,
in _: NSRange,
interaction _: UITextItemInteraction
) -> Bool {
// Disable text attachment interactions
false
}
}
}
#endif