gpt4 book ai didi

ios - UICollectionView 崩溃并出现错误 : Thread 1: EXC_BAD_ACCESS

转载 作者:行者123 更新时间:2023-11-30 11:25:21 24 4
gpt4 key购买 nike

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

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)
}

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

Thread 1: EXC_BAD_ACCESS (code=1, address=0x7a00b0018)

这是输出:

Width: 88.0 (lldb)

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

最佳答案

正如 @rmaddy 和 @Prashant 指出的,

You should not use cellForItemAt in sizeForItemAT because sizeForItemAt is called BEFORE initializing the cell in 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)

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

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

关于ios - UICollectionView 崩溃并出现错误 : Thread 1: EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50796463/

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