ios - swift 3 中的 NSAttributedString 扩展

标签 ios swift swift3

我正在将我的代码迁移到 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 specifying NSStringEncoding for the file;

在较旧的 Swifts 中,NSStringEncoding 常量作为 UInt 导入,因此在转换为 AnyObject 时它们会自动桥接到 NSNumber ,包含在 NSDictionary 中。

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

因此,您需要传递一些可以桥接到 NSNumber 的内容作为键 NSCharacterEncodingDocumentAttribute 的值。在您的情况下,rawValue 会起作用。

在我看来,这应该得到改进,最好将错误报告发送到Appleswift.org .

关于ios - swift 3 中的 NSAttributedString 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39248092/

相关文章:

ios - 如何在swift中使用IAP上传付费应用

database - 如何使用swift 3在核心数据中只获取一列数据

ios - 在 webViewDidFinishLoad 上,我在 swift3 中获得了额外的内容高度

Swift:出现后杀死接收者

swift - CGVectorMake 在 Swift 中不可用

ios - 自定义 MKMarkerAnnotationView 第一次在 UITableViewCell 中无法正确显示

ios - 将委托(delegate)对象类型作为协议(protocol)方法参数传递

ios - 从教程制作简单的 HomeKit 应用程序并在附加 HMAccessory 时出错

ios - avplayer 在 ios 4.3 中不工作

ios - SpriteKit - 多个对象的接触检测