在collectionview中计算高度时,ios swift索引0超出空数组的界限
我想计算HTML字符串上集合视图单元格的高度。HTML字符串通过底部扩展名转换为字符串。但当运行时出现此错误并崩溃时:在collectionview中计算高度时,ios swift索引0超出空数组的界限,ios,swift,uicollectionview,uicollectionviewcell,Ios,Swift,Uicollectionview,Uicollectionviewcell,我想计算HTML字符串上集合视图单元格的高度。HTML字符串通过底部扩展名转换为字符串。但当运行时出现此错误并崩溃时: *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndexedSubscript:]: index 0 beyond bounds for empty array' 我的代码: extension String { v
*** 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>....
blahblah>
asd 。。。。
清理这个。更改:
let htmlToString = artistModel?.biography?.htmlToString
致:
固定的。根据利奥·达布斯的回答:
主线程上的问题已修复。在使用extenstion之前,请在
sizeForItemAt
中将html转换为字符串。它必须在主线程上转换。谢谢大家到底是哪一行导致了错误?你真的需要编写更安全的可选处理方法。@rmaddy当我使用NSString(string:artistModel?.biography!)
它被修复了。但是htmlToString扩展有错误。再说一次,哪一行导致了错误?artistModel
和biography
已准备并存在。不为空
guard let artist = artistModel, let biblio = artist.biography else {return a default size}
let htmlToString = biblio.htmlToString