【问题标题】:Identify Cells in CollectionView识别 CollectionView 中的单元格
【发布时间】:2015-11-28 16:49:26
【问题描述】:

我想在点击的单元格中隐藏标签,而是显示一个图像。另外,我想存储此状态并仅在某个其他单元格已经显示图像时才显示图像。我有一定数量的细胞。 我用 indexPath 做到了,但单元格在滚动时被重用。 如何寻址单元格并存储数据?

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

    println("user tapped on cell number \(indexPath.row)")

    let cell = collectionView.cellForItemAtIndexPath(indexPath) as! MyCollectionViewCell

    if (cell.myLabel.text == "1") {
        one = true

            if (cell.myLabel.hidden) {
                cell.myLabel.hidden = false
                cell.MyImageView.image = nil

            }
            else {
                cell.myLabel.hidden = true
                cell.MyImageView.image = UIImage(named:"1")!
            }
    }

【问题讨论】:

  • 我想你想要一些类似配对游戏的东西。是这样吗?您遇到问题是因为您没有描述确切的问题。 @麦迪
  • 我认为您从错误的方向检查问题;您的数据源服务于视图,而不是相反;因此,您的数据源必须存储有关您的项目的此类信息,显然您只需要更新您的数据源。然后,当您在委托类中显示一个单元格时,您将再次从数据源中提取信息并根据该信息创建视图,该信息已已经存储在那里。

标签: ios swift uicollectionview uicollectionviewcell


【解决方案1】:

您应该将其保存在某个数据源中,而不是将其保存在单元格中。

【讨论】:

    【解决方案2】:

    如果没有在索引路径方法中看到行的单元格,我将假设您没有可以变异的对象数组...否则,您可以向这些对象添加变量而不是可变字典并将其设置为true

    你需要一个可变字典

    var selectedIndexes:NSMutableDictionary = NSMutableDictionary()

    然后当你的单元格被选中时

     override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    
    println("user tapped on cell number \(indexPath.row)")
    
       let keystring = String(format:"%i", indexPath.row)
    
       if self.selectedIndexes[keystring] {
    
           println("cell has been selected before")
    
           // maybe you want to revert the behaviour? 
       }
       else {
    
           self.selectedIndexes.setObject(keystring, forKey: keystring)
    
           let cell = collectionView.cellForItemAtIndexPath(indexPath) as! MyCollectionViewCell
    
           // The criteria wasn't clear when to do you hide code... so whatever you'd like the behaviour to be, check / do it here.
    
       }
    }
    

    然后在

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    
       let keystring = String(format:"%i", indexPath.row)
    
       if self.selectedIndexes[keystring] {
    
       // layout your cell in it's selected state 
    
       }
       else { 
    
       // your normal unselected cell 
    
       }
    
    }
    

    正如我在 cmets 中所说,当您想要某些行为时并不清楚确切的时间......但一个简单的原则是根据与索引路径行相关的键将项目添加到字典中。

    希望有帮助

    【讨论】:

    • 感谢您的回答,但单元格在滚动时仍会重复使用,因此图像会出现在尚未选择的单元格中
    • 这就是cellForItemAtIndexPath 的用途...字典应该在您的视图控制器中而不是在您的单元格中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多