ios - 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
,我想知道问题出在哪里。
解决方案
正如@rmaddy 和@Prashant 指出的那样,
您不应该使用
cellForItemAt
insizeForItemAT
因为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)
现在您已经获得了所需的标签宽度,您可以根据标签的宽度调整项目的大小。
希望有帮助。如果您需要任何帮助,请告诉我。谢谢
推荐阅读
- python-3.x - Boto3 - get_change()、change_resource_record_set() INSYNC 需要 60 秒才能返回
- javascript - 使用函数访问类方法
- python - 从模型创建表单中的相关模型字段中删除“删除选定模型”按钮(Django 管理员)
- c# - 如何将公共(全局)变量分配给 SwitchCell 的 OnProperty(isOn 绑定)以检查是否启用了 SwichCell(打开)
- java - 在 Debug Shell 中执行代码时出现 Eclipse photon 错误
- permissions - 尽管设置了额外的权限,Odoo 11 用户仍无法创建新联系人
- couchdb - couchdb 的 Hyperledger Fabric 性能问题
- java - java中矩阵中的值分配
- java - Spring-integration:如何正确调用 SOAP Web 服务?
- mongodb - 带有父引用的集合的 MongoDB 自连接(聚合)