我尝试访问集合视图中的单元格,然后在用户点击单元格时将字体粗细更改为粗体,但我似乎遇到了一些问题。在我的收藏视图中尝试访问插座时,我收到此错误。
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
但我似乎不明白这一点,因为单元格的标识符是正确的,类名也是正确的。
处理细胞选择的协议
protocol InfiniteCollectionViewDelegate
{
func didSelectCellAtIndexPath(collectionView: UICollectionView, unmodifiedIndexPath: NSIndexPath, usableIndexPath: NSIndexPath)
}
使用协议
extension InfiniteCollectionView: UICollectionViewDelegate
{
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
infiniteDelegate?.didSelectCellAtIndexPath(self, unmodifiedIndexPath: indexPath, usableIndexPath: NSIndexPath(forRow: getCorrectedIndex(indexPath.row - indexOffset), inSection: 0))
}
}
我设置集合视图的方式
func cellForItemAtIndexPath(collectionView: UICollectionView, dequeueIndexPath: NSIndexPath, usableIndexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = navigationCollectionView.dequeueReusableCellWithReuseIdentifier("newsCell", forIndexPath: dequeueIndexPath) as! newsTypeCell
cell.newsTypeLbl.text = cellItems[usableIndexPath.row]
return cell
}
访问集合视图单元格出口的操作
func didSelectCellAtIndexPath(collectionView: UICollectionView, unmodifiedIndexPath: NSIndexPath, usableIndexPath: NSIndexPath)
{
navigationCollectionView.scrollToItemAtIndexPath(unmodifiedIndexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: true)
let cell = navigationCollectionView!.cellForItemAtIndexPath(usableIndexPath) as! newsTypeCell
print(cell.newsTypeLbl.text)
}
答案 0 :(得分:0)
您可以通过安全地展开单元格来防止崩溃。 newsTypeLbl,带有if let语句。
if let label = cell.newsTypeLbl{
label.text = cellItems[usableIndexPath.row]
}
答案 1 :(得分:0)
在这里帮助你的一点是实际使用在该委托方法中传递给你的集合视图:
func didSelectCellAtIndexPath(collectionView: UICollectionView, unmodifiedIndexPath: NSIndexPath, usableIndexPath: NSIndexPath)
{
collectionView.scrollToItemAtIndexPath(unmodifiedIndexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: true)
...
}