Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/117.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 选择时无法在集合视图中获取单元格引用_Ios_Swift_Uicollectionview_Uicollectionviewcell - Fatal编程技术网

Ios 选择时无法在集合视图中获取单元格引用

Ios 选择时无法在集合视图中获取单元格引用,ios,swift,uicollectionview,uicollectionviewcell,Ios,Swift,Uicollectionview,Uicollectionviewcell,我对简单集合视图有一个问题:在delegate didSelectItemAtIndexPath中,我无法获得对单元格的正确引用。这是我的代码: func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection

我对简单集合视图有一个问题:在delegate didSelectItemAtIndexPath中,我无法获得对单元格的正确引用。这是我的代码:

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
{
    return 1
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    return categories.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CategorySelectionCVCell
    cell.titleLabel.text = categories[indexPath.row]["name"] as? String
    cell.backgroundColor = ConversionUtilities.getUIColorFrom(categories[indexPath.row]["color"] as! String)
    return cell
}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CategorySelectionCVCell
    print("Cell with title: \(cell.titleLabel.text) and background color: \(cell.backgroundColor)")
    collectionView.reloadData()
}
当我选择一个单元格时,我总是得到:

标题为:OptionalLabel且背景色为:nil的单元格

我不知道为什么,就像cellForItemAtIndexPath不工作,但cellForItemAtIndexPath中的相同打印给我:

标题为:可选水果和背景色的单元格: 可选UIDeviceRGB颜色空间1 1 0 1

…是的,单元标识符是正确的,是单元,我在情节提要中也正确设置了。此外,UICollectionViewDataSource和UICollectionViewDelegate也在IB中正确链接

有什么帮助吗?

当您使用ReuseIdentifier方法调用dequeueReusableCellWithReuseIdentifier时,即

let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CategorySelectionCVCell
您将得到一个准备好重用的空单元格,而不是当前在集合视图中的单元格

尽管您可以通过调用

let cell = collectionView!.cellForItemAtIndexPath(indexPath) as! CategorySelectionCVCell
如果您只需要标签上的文本,那么最好直接转到模型,即

let labelText = categories[indexPath.row]["name"] as? String