【问题标题】:How to display the HTML text in SwiftUI如何在 SwiftUI 中显示 HTML 文本
【发布时间】:2020-01-14 02:01:19
【问题描述】:

我的要求是在包含HTML 标签的SwiftUI 中显示文本。我尝试了使用WKWebKit::Loadhtml 的方法,效果很好。但是,我需要像这样显示它。 人卡合集

个人卡:- 姓名 职务

具有 HTML 文本的人员详细信息,例如 gHello world

有人可以在SwiftUI 中提出解决此问题的方法吗?

也参考了帖子,但没有运气

How to show HTML or Markdown in a SwiftUI Text?

【问题讨论】:

  • 从字面上看,您链接到的帖子向您展示了如何使用 UIViewRepresentable 在 SwiftUI.View 中包装 WKWebView。您尝试了什么,遇到了什么错误?
  • 我正在寻找一个如何将 UIViewRepresentable 与 UILabel 和属性文本一起使用的示例。但是,我认为使用 WKWebView 派生一个类可以解决问题。如果您有指针,我该如何实现 UIViewRepresentable 然后告诉我。
  • 我正在写一个可以帮助很多像我这样的人的博客

标签: ios swift swiftui swiftui-list


【解决方案1】:

在 SwiftUI 中有多种显示 HTML 文本的方法。但是我发现使用它们有一些问题。连接UILabel 和使用NSAttributedText 只能让我们显示小尺寸字符串,而且WKWebView 限制使用所需的字体。考虑到所有这些,我发现使用 UITextViewNSAttributedText 在 SwiftUI 中显示 HTML 文本更方便。代码如下

import UIKit
import SwiftUI

struct HTMLFormattedText: UIViewRepresentable {

   let text: String
   private  let textView = UITextView()

   init(_ content: String) {
      self.text = content
   }

   func makeUIView(context: UIViewRepresentableContext<Self>) -> UITextView {
      textView.widthAnchor.constraint(equalToConstant:UIScreen.main.bounds.width).isActive = true
      textView.isSelectable = false
      textView.isUserInteractionEnabled = false
      textView.translatesAutoresizingMaskIntoConstraints = false
      textView.isScrollEnabled = false
      return textView
  }

  func updateUIView(_ uiView: UITextView, context: UIViewRepresentableContext<Self>) {
     DispatchQueue.main.async {
         if let attributeText = self.converHTML(text: text) {
             textView.attributedText = attributeText
         } else {
             textView.text = ""
         }

     }
  }

  private func converHTML(text: String) -> NSAttributedString?{
      guard let data = text.data(using: .utf8) else {
          return nil
      }

      if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
          return attributedString
      } else{
          return nil
      }
  }
}

struct ContentView: View {    
    var body: some View {
       HTMLFormattedText("<p>Danish-made 1st class kebab</p><p><br></p><p>Say yes thanks to 2kg. delicious kebab, which is confused and cooked.</p><p><br></p><p>Yes thanks for 149.95</p><p><br></p><p>Now you can make the most delicious sandwiches, kebab mix and much more at home</p>")        
    }
}

这里的高度会根据内容的大小和宽度自动增加。 更多详细信息可在此 GitHub 链接上找到:https://github.com/tmusabe/HTMLFormattedText-SwiftUI

【讨论】:

  • 谢谢。这是所有 stackoverflow 中唯一对我有用的代码!
猜你喜欢
  • 2019-11-15
  • 1970-01-01
  • 2021-07-21
  • 2020-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-15
相关资源
最近更新 更多