1

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>....
Farzad
  • 1,975
  • 1
  • 25
  • 47

2 Answers2

1

Clean this up. Change:

let htmlToString = artistModel?.biography?.htmlToString

to:

guard let artist = artistModel, let biblio = artist.biography else {return a default size}

let htmlToString = biblio.htmlToString
rmaddy
  • 314,917
  • 42
  • 532
  • 579
shayegh
  • 302
  • 1
  • 9
0

Fixed. according answer by @Leo Dabus: https://stackoverflow.com/a/28132610/2303865

problem fixed on Main Thread. before using extenstion convert html to string in sizeForItemAt. it must convert on main thread. thanks all

Farzad
  • 1,975
  • 1
  • 25
  • 47