forked from gonzalezreal/AttributedText
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAttributedText.swift
54 lines (48 loc) · 1.86 KB
/
AttributedText.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
import SwiftUI
/// A view that displays styled attributed text.
public struct AttributedText: View {
private var textSizeViewModel = TextSizeViewModel()
@State private var textSize: CGSize?
private let attributedText: NSAttributedString
private let onOpenLink: ((URL) -> Void)?
/// Creates an attributed text view.
/// - Parameters:
/// - attributedText: An attributed string to display.
/// - onOpenLink: The action to perform when the user opens a link in the text. When not specified,
/// the view opens the links using the `OpenURLAction` from the environment.
public init(_ attributedText: NSAttributedString, onOpenLink: ((URL) -> Void)? = nil) {
self.attributedText = attributedText
self.onOpenLink = onOpenLink
}
/// Creates an attributed text view.
/// - Parameters:
/// - attributedText: A closure that creates the attributed string to display.
/// - onOpenLink: The action to perform when the user opens a link in the text. When not specified,
/// the view opens the links using the `OpenURLAction` from the environment.
public init(attributedText: () -> NSAttributedString, onOpenLink: ((URL) -> Void)? = nil) {
self.init(attributedText(), onOpenLink: onOpenLink)
}
public var body: some View {
GeometryReader { geometry in
AttributedTextImpl(
attributedText: attributedText,
maxLayoutWidth: geometry.maxWidth,
textSizeViewModel: textSizeViewModel,
onOpenLink: onOpenLink
)
}
.frame(
idealWidth: textSize?.width,
idealHeight: textSize?.height
)
.fixedSize(horizontal: false, vertical: true)
.onReceive(textSizeViewModel.$textSize) { size in
textSize = size
}
}
}
extension GeometryProxy {
fileprivate var maxWidth: CGFloat {
size.width - safeAreaInsets.leading - safeAreaInsets.trailing
}
}