簡體   English   中英

Xcode 9.1 Swift 4,如果使用“if #available”,則無法使用 NSDocumentTypeDocumentAttribute 進行編譯

[英]Xcode 9.1 Swift 4, unable to compile with NSDocumentTypeDocumentAttribute if “if #available” is used

嗨,我的應用程序在部署目標設置中針對 iOS8.2。 我試圖將應用程序從 swift3 轉換為 swift 4。 它可以工作,但不能在 iPhone 5s iOS 8.4 的模擬器中工作。 問題是這樣的:

cell.lblHeader.attributedText = try NSAttributedString(data: htmlData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)

所以我試過這個:

if #available(iOS 11, *){
     cell.lblHeader.attributedText = try NSAttributedString(data: htmlData, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
}
if #available(iOS 8.4, *){
     cell.lblHeader.attributedText = try NSAttributedString(data: htmlData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
}

但我無法編譯此代碼 Xcode 顯示 iOS 8.4 分支異常:

Cannot convert value of type 'NSAttributedString.DocumentAttributeKey' to expected dictionary key type 'NSAttributedString.DocumentReadingOptionKey'

我有關於將基礎 sdk 設置為 8.x 的意見,但我沒有找到這樣做的機會。 在構建設置中,我只能將基礎 sdk 設置為 11.x 版本。

我會感謝每一個想法。

僅使用此行:

cell.lblHeader.attributedText = try NSAttributedString(data: htmlData, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)

似乎這是Swift 4.1.2的正確語法

let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
            NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,
            NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue
        ]

它適用於 Swift 4.0:

let documentKey = NSAttributedStringKey("NSDocumentTypeDocumentAttribute")
let charsetKey = NSAttributedStringKey("NSCharacterEncodingDocumentAttribute")
let string = NSAttributedString(string: htmlString,
                                attributes: [documentKey: NSAttributedString.DocumentType.html,
                                             charsetKey: String.Encoding.utf8.rawValue])

它適用於 swift 5。

    let htmlString = """
    <html>
      <head><style type=\"text/css\">body { font-family: Mehr Nastaliq Web; font-size: 22pt; white-space: pre-wrap; text-align: right; lang: en; direction: RTL; -webkit-user-select: none; meta charset=\"UTF-8\" }</style> </head>
      <body leftmargin=\"20\" topmargin=\"0\" rightmargin=\"20\">hello world! Arabic.مُدّعا عَنقا ہے اپنے عالَمِ تقریر کا میری تقریر کا مفہوم چونکہ عنقا یعنی معدوم ہے اور معدوم </body>
   </html>
    """

    let attributedString = try? NSAttributedString(data:
        htmlString.data(using: String.Encoding.unicode)!, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)

暫無
暫無

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

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