From c42537d885c719748084db22161bc7c15e53e4ad Mon Sep 17 00:00:00 2001 From: redstrate <54911369+redstrate@users.noreply.github.com> Date: Thu, 4 Jun 2020 06:35:41 -0400 Subject: [PATCH] Add support for rendering html post content --- MobileFort/MobileFort/PostView.swift | 33 +++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/MobileFort/MobileFort/PostView.swift b/MobileFort/MobileFort/PostView.swift index a7107d6..d1be143 100644 --- a/MobileFort/MobileFort/PostView.swift +++ b/MobileFort/MobileFort/PostView.swift @@ -7,6 +7,37 @@ extension String { } } +/// A custom view to use NSAttributedString in SwiftUI +struct AttributedText: UIViewRepresentable { + func updateUIView(_ uiView: UILabel, context: Context) { + + } + + let html: String + + init(_ html: String) { + self.html = html + } + + public func makeUIView(context: UIViewRepresentableContext) -> UILabel { + let textView = UILabel() + textView.backgroundColor = .clear + textView.lineBreakMode = .byWordWrapping + textView.numberOfLines = 0 + textView.lineBreakMode = .byWordWrapping + textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + + DispatchQueue.main.async { + let data = Data(self.html.utf8) + if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) { + textView.attributedText = attributedString + } + } + + return textView + } +} + struct PostView: View { let post: Post @@ -53,7 +84,7 @@ struct PostView: View { } } - Text(post.getContent()) + AttributedText(post.getContent()).frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity) } }.frame(maxWidth: .infinity) }