gpt4 book ai didi

在collectionview中计算高度时,ios swift index 0超出了空数组的范围

转载 作者:行者123 更新时间:2023-12-01 22:15:24 25 4
gpt4 key购买 nike

我想计算 HTML 字符串上 Collection View 单元格的高度。 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>....

最佳答案

清理这个。改变:

let htmlToString = artistModel?.biography?.htmlToString

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

let htmlToString = biblio.htmlToString

关于在collectionview中计算高度时,ios swift index 0超出了空数组的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52194062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com