Невозможно преобразовать значение типа «NSAttributedString.DocumentAttributeKey», «DocumentReadingOptionKey» также не работает - PullRequest
1 голос
/ 18 апреля 2019

Я перешел с 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 голосов
/ 18 апреля 2019

Попробуйте это

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
}
0 голосов
/ 18 апреля 2019

Значение, которое вы пытаетесь передать параметру 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)
...