我从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")
})
这是我的错误:
无法将类型“ NSAttributedString.DocumentAttributeKey”的值转换为预期的字典密钥类型“ NSAttributedString.DocumentReadingOptionKey”
阅读一些发布的问题和解决方案,尝试将NSAttributedString.DocumentAttributedKey
更改为NSAttributedString.DocumentReadingOptionKey
,但仍然出现错误。
答案 0 :(得分:0)
您试图传递给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)
答案 1 :(得分:0)
尝试
var htmlString: String = "<html><head><style xxxxxx </style></head><body>\(message)</body></html>"
if let attributedString = try? NSAttributedString(data: (htmlString.data(using: .unicode, allowLossyConversion: true)!), options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
self.lblDetail.attributedText = attributedString
}