在CollectionViewCell中准备ForReuse

时间:2015-11-28 14:28:46

标签: ios swift uicollectionviewcell collectionview prepareforreuse

我想在被点击的单元格中隐藏标签,而是显示图像。但是,只有当具有特定索引的单元格已经设置为imageView时,我才想这样做。 如果将单元格设置为imageView,则解决单元格和存储的最佳方法是什么?我如何使用prepareForReuse方法?

这是我直到现在的方式,但随着细胞的重复使用。滚动时图像显示在其他单元格中。

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

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

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

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

        if(seven = true) {

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

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

         }
    }

2 个答案:

答案 0 :(得分:0)

你没有说你的集合视图是否有7个单元格,或者它是否可以在集合中有“N”(例如100个)单元格,所以如果这是我的问题并且我必须解决它,我会您的“seven”单元格的状态是该类的属性(例如“var sevenState : Bool”),然后我可以显示其他单元格的按钮或图像,具体取决于sevenState

答案 1 :(得分:0)

在我的应用程序中,我必须根据索引路径配置UICollectionReusableView,如果indexPath具有特定值,则我发送一个用于设置标签和图像的数组。

我在自定义UICollectionReusableView中使用了一个函数,如果我用数组调用它,它会填充标签和图像,如果我用nil调用它,它会重置它们。

func collectionView(collectionView: UICollectionView!, viewForSupplementaryElementOfKind kind: String!, atIndexPath indexPath: NSIndexPath!) -> UICollectionReusableView!  {
     .... [logic around selecting index path based on data returned]
     .... 
   if filteredEvents != nil{
            reusableView.populateCalendarDayDates(sortedEvents)
   }else{
            reusableView.populateCalendarDayDates(nil)
   }

在自定义UICollectionReusableView的函数中,我将标签重置为默认值,然后才更新它们:

func populateCalendarDayDates(arrayEvents: NSArray?){
    let firstDayTag = tagStartDay()
    var dayDate = 1

    for var y = 1; y < 43; y++ {
        let label = self.viewWithTag(y) as! BGSCalendarMonthLabel
        label.delegate = callingCVC
        label.backgroundColor = UIColor.clearColor()
        label.textColor = UIColor.whiteColor()

        label.text = ""

通过将此代码移动到自定义UICollectionReusableView中的prepareForReuse,您可以获得相同的效果,并且可能更具可读性:

override func prepareForReuse() {
    super.prepareForReuse()
    for var y = 1; y < 43; y++ {
        let label = self.viewWithTag(y) as! BGSCalendarMonthLabel
        label.backgroundColor = UIColor.clearColor()
        label.textColor = UIColor.whiteColor()

        label.text = ""
    }

}

希望有所帮助。