Swift 无法访问uicollectionview单元格
我试图访问集合视图中的一个单元格,然后当用户点击该单元格时,将字体大小更改为粗体,但我似乎遇到了一些问题。当尝试在我的收藏视图中访问Outlet时,我遇到此错误Swift 无法访问uicollectionview单元格,swift,uicollectionview,uicollectionviewcell,Swift,Uicollectionview,Uicollectionviewcell,我试图访问集合视图中的一个单元格,然后当用户点击该单元格时,将字体大小更改为粗体,但我似乎遇到了一些问题。当尝试在我的收藏视图中访问Outlet时,我遇到此错误 fatal error: unexpectedly found nil while unwrapping an Optional value (lldb) 但我似乎不理解这一点,因为单元格的标识符是正确的,类名也是正确的 处理单元格选择的协议 protocol InfiniteCollectionViewDelegate {
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)
}
您可以通过安全地展开单元格来防止崩溃的发生。带有if-let语句的newsTypeLbl
if let label = cell.newsTypeLbl{
label.text = cellItems[usableIndexPath.row]
}
在这里,可以帮助您实际使用在该委托方法中传递给您的集合视图:
func didSelectCellAtIndexPath(collectionView: UICollectionView, unmodifiedIndexPath: NSIndexPath, usableIndexPath: NSIndexPath)
{
collectionView.scrollToItemAtIndexPath(unmodifiedIndexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: true)
...
}
我正在尝试打印标签中的值,并且已经尝试了您建议的方法,如果让label=cell.newsTypeLbl{print(label.text)},则执行此操作
let cell=navigationCollectionView!。cellForItemAtIndexPath(usableIndexPath)为!newsTypeCell
相同的致命错误:在展开可选值(lldb)时意外发现nil