i want calculate height of collection view cell on HTML string. HTML string converted to string by bottom extension. but when runtime this error and crash:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndexedSubscript:]: index 0 beyond bounds for empty array'
my code:
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 ?? ""
}
}
in method cellForItemAt
:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//let cell = ....
cell?.biographyTextView.text = artistModel?.biography?.htmlToString
}
and in method 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)
}
biography text is for example:
<p>blahblah><br /><br/><li>asd</li>....