繁体   English   中英

CollectionViewCell中的PrepareForReuse

[英]PrepareForReuse in CollectionViewCell

我想将标签隐藏在已点击的单元格中,而不是显示图像。 但是,仅当具有特定索引的单元格已设置为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")!
            }

         }
    }

您没有说集合视图中是否恰好有7个单元格,或者集合视图中是否可以有“ N”个(例如100个)单元格,所以如果这是我的问题并且必须解决,我将确定您的状态“ seven ”单元是类的一个属性(例如“ var sevenState : Bool ”),然后我可以根据sevenState是什么来显示其他单元的按钮或图像。

在我的应用程序中,我必须基于索引路径配置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 = ""
    }

}

希望能有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM