无法转换类型为'NSAttributedString.DocumentAttributeKey'的值,“ DocumentReadingOptionKey”也不起作用

时间:2019-04-18 04:34:31

标签: 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")
})

这是我的错误:

  

无法将类型“ NSAttributedString.DocumentAttributeKey”的值转换为预期的字典密钥类型“ NSAttributedString.DocumentReadingOptionKey”

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

2 个答案:

答案 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
}