我想计算HTML字符串上集合视图单元格的高度。 HTML字符串由底部扩展名转换为字符串。但是在运行时出现此错误并崩溃:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndexedSubscript:]: index 0 beyond bounds for empty array'
我的代码:
extension String {
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) else { return NSAttributedString() }
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
var htmlToString: String {
return htmlToAttributedString?.string ?? ""
}
}
在方法cellForItemAt
中:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//let cell = ....
cell?.biographyTextView.text = artistModel?.biography?.htmlToString
}
和方法sizeForItemAt
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let htmlToString = artistModel?.biography?.htmlToString
let size = CGSize(width: collectionView.frame.width, height: .greatestFiniteMagnitude)
let attributes = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 15)]
let estimatedFrame = NSString(string: htmlToString!).boundingRect(with: size, options: [.usesFontLeading, .usesLineFragmentOrigin], attributes: attributes, context: nil)
return CGSize(width: collectionView.frame.width, height: estimatedFrame.height)
}
传记文字例如:
<p>blahblah><br /><br/><li>asd</li>....
答案 0 :(得分:1)
清理一下。更改:
let htmlToString = artistModel?.biography?.htmlToString
收件人:
guard let artist = artistModel, let biblio = artist.biography else {return a default size}
let htmlToString = biblio.htmlToString
答案 1 :(得分:0)
已修复。根据 @Leo Dabus 的回答:https://stackoverflow.com/a/28132610/2303865
问题已在主线程上修复。在使用扩展功能之前,请将html转换为sizeForItemAt
中的字符串。它必须在主线程上转换。谢谢大家