Swift:如何在没有属性字符串的情况下在文本视图中显示粗体字



我们正在为我们正在处理的应用程序添加修饰触摸,这显然意味着放置整个"条款和条件"one_answers"常见问题解答"部分,格式化,子弹,打破,打破和所有。

所以我尝试将其复制到带有"可编辑"的文本视图中,这使子弹保持了,但不保留大胆的文本。

现在,我以前曾做过归因于字符串,我不得不说,我不确定在价值12页的段落,项目符号列表和休息时间可能会发生变化是否容易做到这一点几年左右。

所以我的问题是,有没有使用属性字符串的方法来执行此操作?

禁止这一点,也许有一种方法可以循环浏览文本,并寻找将应用属性的书面标签?

编辑:

更新。有人建议我使用HTML标签和Web视图。这就是为常见问题解答(使用标签)所做的,我也忽略了我也尝试了。

出于某种原因,它只是显示一个空白的文本视图,尽管它是一个大型的文本视图,好像其中有文本(没有任何文本)。奇怪的是,拷贝性可以是有效的。

这是我的代码:

override func awakeFromNib() {
    super.awakeFromNib()
    termsTitle.text = "Terms and Conditions"
    htmlContent = "<p style="font-family:Helvetica Neue"><br/><strong><br/> BLA BLA BLA BLA BLA BLA x 12 Pages"
    do {
        let str = try NSAttributedString(data: htmlContent.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
        termsTextView.attributedText = str
    } catch {
        print("Dim background error")
    }
}

我敢肯定,如果不使用属性string,您就无法在文本视图中执行此操作。可能的解决方案是使用WebView。将您的"条款和条件"one_answers" FAQ"转换为HTML可能比使用属性string容易得多。

如果您仍然想在UITEXTVIEW中使用HTML,则可以尝试此功能:

func getAttributedString(fileName: String) -> NSAttributedString? {
   if let htmlLocation = NSBundle.mainBundle().URLForResource(fileName, withExtension: "html"), data = NSData(contentsOfURL: htmlLocation) {
      do {
         let attrString = try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType], documentAttributes: nil)
         return attrString
      } catch let err as NSError {
         print("Attributed String Creation Error")
         print(err.localizedDescription)
         return nil
      }
   } else {
      return nil
   }
}

此功能假设您的主捆绑包中有一个.html文件。您将其传递给文件的名称(减去扩展名)(应该在您的项目中),然后像这样使用:

textView.attributedText =  getAttributedString("TermsAndConditions")

只是为了澄清,在此示例中,文本视图是视图控制器上的@IBOutlet

如果.html文件不存在或NSAttributtedString转换失败,则此功能将返回零。

相关内容

最新更新