繁体   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