【发布时间】:2018-06-11 11:14:16
【问题描述】:
本来我的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)
}
这是一个错误报告,它显示在class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {:
线程 1:EXC_BAD_ACCESS(代码=1,地址=0x7a00b0018)
这是输出:
宽度:88.0 (lldb)
我的班级继承了UICollectionViewDelegateFlowLayout,我想知道问题出在哪里。
【问题讨论】:
-
您不应访问 .
sizeForItemAt方法 -
@PrashantTukadiya那么如何动态调整宽度?
-
标签没有被初始化,所以你不能访问它。检查这个stackoverflow.com/questions/28409390/…
-
在
let cell...之后立即调用cell.awakeFromNib()可能会有所帮助。 -
永远不要在
cellForItemAt之外使用dequeueReusableCell。
标签: ios swift uicollectionview uikit