swift - 无法转换类型 'NSAttributedString.DocumentAttributeKey' 的值, "DocumentReadingOptionKey"也不起作用

标签 swift swift4 nsattributedstring

我从 Swift 3 升级到 Swift 4,我得到了 NSAttributedString 相关的错误。

这是我的代码:

viewModel.getInviteAFriendInfo(success: { message in
    if message.isEmpty{
        self.lblDetail.text = "xxxxxxx"
    }else{
        let htmlString: String = "<html><head><style xxxxxx </style></head><body>\(message)</body></html>"
        self.lblDetail.setText(try! NSAttributedString(data: htmlString.data(using: .unicode, allowLossyConversion: true)!, options: [NSAttributedString.DocumentAttributeKey.documentType:NSAttributedString.DocumentType.html,NSAttributedStringKey.kern: 2.0], documentAttributes: nil))
    }
}, failure: {
    self.showAlert("Failed to get text")
})

这是我的错误:

Cannot convert value of type 'NSAttributedString.DocumentAttributeKey' to expected dictionary key type 'NSAttributedString.DocumentReadingOptionKey'

阅读一些已发布的问题和解决方案,尝试将 NSAttributedString.DocumentAttributedKey 更改为 NSAttributedString.DocumentReadingOptionKey,但仍然出错。

最佳答案

您尝试传递给 options 参数的值需要拆分。

首先,documentType 来自 NSAttributedString.DocumentReadingOptionKey,而不是 NSAttributedString.DocumentAttributeKey

其次,kern 需要传递给 documentAttributes 参数,而不是 options 参数。

如果你拆分代码会容易得多:

let options: [NSAttributedString.DocumentReadingOptionKey : Any] = [ .documentType: NSAttributedString.DocumentType.html ]
let attributes = [ NSAttributedString.Key.kern: 2.0 ] as NSDictionary?
let data = htmlString.data(using: .utf8)!
let attrStr = try? NSAttributedString(data: data, options: options, documentAttributes: &attributes)

关于swift - 无法转换类型 'NSAttributedString.DocumentAttributeKey' 的值, "DocumentReadingOptionKey"也不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55739204/

相关文章:

ios - Swift 链接错误 : type metadata accessor for Module. 类

ios - 在 UITableViewCell 中逐行显示字符串的动画

ios - SpriteKit - 接触错误

使用 `ReferenceWritableKeyPath ` 的 Swift 编译器段错误

ios - UITextView 我应该在哪里设置属性字符串的颜色和字体

ios - NSAttributedString背景颜色和圆角

swift - Swift 中展开的可选数组的相等性

ios - 结束异步进程的正确方法

Swift 4 协议(protocol)组合一致性

ios - 如何使用 Swift 在 iOS 中使用 NSAttributedStrings?