我正在将我的代码迁移到 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
这就是我从 View Controller 调用方法的方式
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
}
}
如 the official reference 中所述,键 NSCharacterEncodingDocumentAttribute
的值需要是 NSNumber
。
NSCharacterEncodingDocumentAttribute
The value of this attribute is an
NSNumber
object containing integer specifyingNSStringEncoding
for the file;
在较旧的 Swifts 中,NSStringEncoding
常量作为 UInt
导入,因此在转换为 AnyObject 时它们会自动桥接到
,包含在 NSNumber
NSDictionary
中。
但是现在,Swift 引入了一种新的枚举类型 String.Encoding
,它并非起源于 Objective-C 枚举。不幸的是,现在任何 Swift 类型都可以包含在具有中间隐藏引用类型 _SwiftValue
的 NSDictionary
中,这绝对不是 NSNumber
。
因此,您需要传递一些可以桥接到 NSNumber
的内容作为键 NSCharacterEncodingDocumentAttribute
的值。在您的情况下,rawValue
会起作用。
关于ios - swift 3 中的 NSAttributedString 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39248092/