首页 > 解决方案 > UICollectionView 崩溃并出现错误:线程 1:EXC_BAD_ACCESS

问题描述

本来我的CollectionView工作的很好,但是我想根据CollectionView中TextLabel的宽度来调整CollectionView中item的宽度,所以我加了一些代码然后在程序初始化的时候crash了:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "OnedaySubTodoCell", for: indexPath) as! SubCell
    let width = 28 + cell.subNameLabel.bounds.size.width
    print("Width: \(width)")
    return CGSize(width: width, height: 20)
}

这是一个错误报告,它显示在class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

线程 1:EXC_BAD_ACCESS(代码=1,地址=0x7a00b0018)

这是输出:

宽度:88.0 (lldb)

我的类继承了UICollectionViewDelegateFlowLayout,我想知道问题出在哪里。

标签: iosswiftuicollectionviewuikit

解决方案


正如@rmaddy 和@Prashant 指出的那样,

您不应该使用cellForItemAtinsizeForItemAT因为 sizeForItemAt在初始化单元格之前调用 cellForItemAt

很可能这就是你崩溃的原因。走向解决方案。

我遇到了类似的问题(必须动态管理高度),我所做的是类似的

根据文本计算标签的估计宽度。使用以下字符串扩展名

//calculates the required width of label based on text. needs height and font of label
extension String {

 func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {

    let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
    let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil)

    return ceil(boundingBox.width)
  }
}

现在,里面sizeForItemAt

    //put actual lblHeight here
    let lblHeight = Put_actual_label_height_here // e.g 30

    //put actual label font here
    let lblFont =   Put_actual_label_font_here  //e.g UIFont.boldSystemFont(ofSize: 20)

  //calculate required label width
    let lblRequiredWidth = yourLabel's_Text_String.width(withConstrainedHeight: lblHeight, font: lblFont)

    //you may want to return size now 
    let height = yourItemsHeight
    return CGSize(width: lblRequiredWidth, height: height)

现在您已经获得了所需的标签宽度,您可以根据标签的宽度调整项目的大小。

希望有帮助。如果您需要任何帮助,请告诉我。谢谢


推荐阅读