簡體   English   中英

Swift:如何在沒有屬性字符串的情況下在TextView中顯示粗體字

[英]Swift: how to display bold words in textview without attributed string

我們正在為正在開發的應用程序添加畫龍點睛的功能,這顯然意味着要放置完整的“條款和條件”和“常見問題解答”部分,以及格式,項目符號,中斷和所有內容。

因此,我嘗試將其復制粘貼到關閉了“可編輯”的textView中,以保留項目符號,但不保留粗體文本。

現在,我之前已經完成了屬性字符串的使用,我不得不說,我不確定在幾年后可能會發生變化的價值約12頁的段落,項目符號列表和中斷中這樣做是否容易或者。

所以我的問題是,有沒有一種方法可以不使用屬性字符串呢?

除此以外,也許有一種方法可以遍歷文本並尋找將應用屬性的書面標記?

編輯:

更新。 建議使用HTML標記和Web視圖。 這是針對FAQ(使用標簽)所做的,我忽略了我也嘗試過的做法。

由於某種原因,它只是顯示一個空白的textview,盡管是一個大的textview,好像其中有文本(沒有任何文本)。 奇怪的是,粘貼粘貼有效,但事實並非如此。

這是我的代碼:

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")
    }
}

我敢肯定,如果不使用AttributedString,則無法在Textview中執行此操作。 一種可能的解決方案是使用WebView。 將“條款和條件”和“ FAQ”轉換為HTML可能比使用AttributedString容易得多。

如果仍要在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 ,在此示例中, @IBOutlet是視圖控制器上的@IBOutlet

如果.html文件不存在或NSAttributedString轉換失敗,則此函數返回nil。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM