swift 3 中的 NSAttributedString 扩展

2023-12-20

我正在将我的代码迁移到 swift 3,但我在使用之前的 swift 版本上运行的扩展时遇到了困难。

extension Data {
    var attributedString: NSAttributedString? {
        do {
            return try NSAttributedString(data: self, options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8], documentAttributes: nil)
        } catch let error as NSError {
            print(error.localizedDescription)
        }
        return nil
    }
}

现在,当我尝试调用这段代码时,我收到如下异常错误

error: warning: couldn't get required object pointer (substituting NULL): Couldn't load 'self' because its value couldn't be evaluated

这就是我从视图控制器调用该方法的方式

let htmlCode = "<html><head><style type=\"text/css\">@font-face {font-family: Avenir-Roman}body {font-family: Avenir-Roman;font-size:15;margin: 0;padding: 0}</style></head><body bgcolor=\"#FBFBFB\">" + htmlBodyCode + "</body>"
newsDescription.attributedText = htmlCode.utf8Data?.attributedString

尝试这个:

extension Data {
    var attributedString: NSAttributedString? {
        do {
            return try NSAttributedString(data: self, options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch let error as NSError {
            print(error.localizedDescription)
        }
        return nil
    }
}

如中所述官方参考 https://developer.apple.com/reference/uikit/nscharacterencodingdocumentattribute,键的值NSCharacterEncodingDocumentAttribute需要是一个NSNumber.

NSCharacterEncodingDocumentAttribute

该属性的值为NSNumber包含指定整数的对象NSStringEncoding对于文件;

在较老的雨燕中,NSStringEncoding常量导入为UInts,因此它们会自动桥接到NSNumber当转换为AnyObject,如包含在NSDictionary.

但现在,Swift 引入了一种新的枚举类型String.Encoding它并非源自 Objective-C 枚举。不幸的是,现在任何 Swift 类型都可以包含在NSDictionary具有中间隐藏引用类型_SwiftValue,这绝对不是NSNumber.

所以,你需要传递一些可以桥接的东西NSNumber作为键的值NSCharacterEncodingDocumentAttribute。就你而言,rawValue会工作。

我认为这应该改进,最好将错误报告发送给Apple http://developer.apple.com/bug-reporting/ or swift.org https://bugs.swift.org/.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

swift 3 中的 NSAttributedString 扩展 的相关文章

随机推荐