Xcode 9.1 Swift 4,如果使用“if #available”,则无法使用 NSDocumentTypeDocumentAttribute 进行编译

问题描述 投票:0回答:4

您好,我有一个应用程序在部署目标设置中以 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 版本。

我会感谢每一个想法。

ios swift xcode
4个回答
30
投票

仅使用此行:

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

15
投票

这似乎是 Swift 4.1.2 的正确语法:

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

0
投票

它与 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])

0
投票

它可以在 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)
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.