分段重复单元格的集合视图

时间:2016-09-20 09:24:06

标签: ios swift uicollectionview uisegmentedcontrol

我在使用带有segmentView的集合视图时出现问题。

我的viewController有一个 segmentView ,包含4个元素(0 =>全部,1 =>照片,2 => Audios,3 => ;视频) 这里和例子:

enter image description here

我有一个 collectionView 来显示数据,具体取决于从 segmentController

点击的类别

它正在工作并显示数据,这是我的 collectionView 方法来显示数据

 // MARK: Datasource collection method

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // All Items

        if segmentStatues == 0
        {
            let cellForAll = collectionView.dequeueReusableCell(withReuseIdentifier: "AllItemsCell", for: indexPath) as! AllItemsCollectionViewCell

            // reset elements before declare

            cellForAll.cellImage.image = nil
            cellForAll.playBtn.isHidden = true

            cellForAll.layer.borderWidth = 1
            cellForAll.layer.borderColor = UIColor(red:0.93, green:0.93, blue:0.93, alpha:1.0).cgColor
            // When type is an image
            if sociaPosts[(indexPath as NSIndexPath).row].postType == "image"
            {

                cellForAll.cellImage.sd_setImage(with: URL(string: sociaPosts[(indexPath as NSIndexPath).row].postUrl))


            }else if sociaPosts[(indexPath as NSIndexPath).row].postType == "audio"
            {

                cellForAll.cellImage.image  = UIImage(named: "recorde_icon")


            }else if sociaPosts[(indexPath as NSIndexPath).row].postType == "video"
            {
                cellForAll.cellImage.sd_setImage(with: URL(string: sociaPosts[(indexPath as NSIndexPath).row].thumbURL))
                cellForAll.playBtn.isHidden = false
            }

            return cellForAll

        }else{

            // Cell if Images or videos or audios

            let newCell = collectionView.dequeueReusableCell(withReuseIdentifier: "beepbeep", for: indexPath) as! userProfileImageCollectionViewCell

            // If the type is images

            if  segmentStatues == 1
            {   
                // Set image URL

                newCell.cellImage.sd_setImage(with: URL(string: imagesPosts[(indexPath as NSIndexPath).row].postUrl))

                // Get image likes and comments and shares

                newCell.likeCount.text = String(imagesPosts[(indexPath as NSIndexPath).row].likes_count)
                newCell.commentCount.text = String(imagesPosts[(indexPath as NSIndexPath).row].comments_count)
                newCell.shareCount.text = String(imagesPosts[(indexPath as NSIndexPath).row].shares_count)

            } else if segmentStatues == 3
            {
                // For Video player

             var player = newCell.customVid
            player = Bundle.main.loadNibNamed("VieoPlayer", owner: self, options: nil)?.last as? videoPlayer

           player?.newIntitVideoPlayer(forViewController: self, videoURL: videosPosts[indexPath.row].postUrl , videoThumbnail: URL(string: videosPosts[indexPath.row].thumbURL), onReady: nil)
                // Set video URL and Thumbnail

                // Get video likes and comments and shares
                newCell.likeCount.text = String(videosPosts[(indexPath as NSIndexPath).row].likes_count)
                newCell.commentCount.text = String(videosPosts[(indexPath as NSIndexPath).row].comments_count)
                newCell.shareCount.text = String(videosPosts[(indexPath as NSIndexPath).row].shares_count)

            }else if segmentStatues == 2
            {
                // Audio player
                let ad = Bundle.main.loadNibNamed("AudioPlayerView", owner: self, options: nil)?.last as! AudioPlayerView
                ad.frame = CGRect(x: (newCell.contentView.frame.size.width - newCell.contentView.frame.size.height * 0.6) / 2, y: 20 , width: newCell.contentView.frame.size.height * 0.6, height: newCell.contentView.frame.size.height * 0.6)
                ad.playImageView.image = nil

                ad.tag = 6666

                newCell.contentView.addSubview(ad)

                // Set audio URL
                ad.audioPath = URL(string: audiosPosts[indexPath.row].postUrl)
                ad.viewInitialization()

                // Get Audio  likes and comments and shares
                newCell.likeCount.text = String(audiosPosts[(indexPath as NSIndexPath).row].likes_count)
                newCell.commentCount.text = String(audiosPosts[(indexPath as NSIndexPath).row].comments_count)
                newCell.shareCount.text = String(audiosPosts[(indexPath as NSIndexPath).row].shares_count)   

            }
            return newCell
        } 
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        if self.segmentStatues == 0
        {

            return  sociaPosts.count
        }else if self.segmentStatues == 1
        {
            return imagesPosts.count
        }else if self.segmentStatues == 2
        {
            return audiosPosts.count
        }else
        {
            return videosPosts.count
        }
    }

我的收藏夹中有2个自定义单元格,一个用于所有项目,另一个用于(图像 - 音频 - 视频)视图

我的问题是数据显示但是当我在 userProfileImageCollectionViewCell

中的段之间进行更改时,单元格会重复

这两张照片显示了问题

单击音频segmnet时显示所有音频单元

enter image description here

但是我点击图像或视频片段后,像这样复制了

enter image description here

它发生在音频 - 图像 - 仅限视频**(userProfileImageCollectionViewCell)**

最后这是我的userProfileImageCollectionViewCell代码:

更新:

import UIKit
import SDWebImage
class userProfileImageCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var customVid: videoPlayer!
    @IBOutlet weak var cellImage: UIImageView!

    @IBOutlet weak var likeButton: UIButton!

    @IBOutlet weak var likeCount: UILabel!
    @IBOutlet weak var commentButton: UIButton!

    @IBOutlet weak var commentCount: UILabel!
    @IBOutlet weak var shareButton: UIButton!
    @IBOutlet weak var shareCount: UILabel!

    override func prepareForReuse() {
        cellImage.sd_setImage(with: nil)
       self.customVid.subviews.forEach({ $0.removeFromSuperview() })

    }
}

1 个答案:

答案 0 :(得分:1)

问题在于,UICollectionViewCell(以及顺便提出的UITableViewCell)会被重复使用。

简单地说: 滚动时,当一个单元格从屏幕上消失时,它可能会返回顶部/底部(根据滚动方向)。但它不是一个新的“干净”细胞,它是前一个细胞。这就是重用系统。

因此,当您执行:newCell.contentView.addSubview(ad)时,您每次都会添加一个新的子视图,而不会检查是否已有。 juste打桩的子视图。使用3D Hierarchy Debug of XCode检查它很容易。

由于您有userProfileImageCollectionViewCell个文件,因此最佳解决方案是使用prepareForReuse()。 创建一个IBOutlet(我们称之为customVid),将其添加为广告/播放器的子视图。 在prepareForReuse()中删除customVid的所有子视图。 在collectionView:cellForRowAtIndexPath:中,执行类似的操作:

var player = Bundle.main.loadNibNamed("VieoPlayer", owner: self, options: nil)?.last as? videoPlayer 
player?.newIntitVideoPlayer(forViewController: self, videoURL: videosPosts 
newCell.customVid.addSubview(player)

ad复制相同的机制(您可以使用相同的子视图,这取决于您)。

现在,一些与您的问题无关的建议:

以大写字母命名您的班级:userProfileImageCollectionViewCell => UserProfileImageCollectionViewCell

我会在userProfileImageCollectionViewCell中创建方法,以使您的代码更具可读性。我不会说Swift,所以我的下一行代码可能无法编译,但你应该明白这个想法:

func fillWithVideo(videoParam video: CustomVideoClass) {
     var player = newCell.customVid
     player = Bundle.main.loadNibNamed("VieoPlayer", owner: self, options: nil)?.last as? videoPlayer
     player?.newIntitVideoPlayer(forViewController: NOTself, videoURL: video.postUrl, videoThumbnail: URL(string: video.thumbURL), onReady: nil)
    self.customVid.addSubview(player)
    // Set video URL and Thumbnail

    // Get video likes and comments and shares
     self.likeCount.text = String(video.likes_count)
     self.commentCount.text = String(video.comments_count)
     self.shareCount.text = String(video.shares_count)
}

collectionView:cellForRowAtIndexPath:

//If it's the correct section
let video = videosPosts[(indexPath as NSIndexPath).row] as CustomVideoClass
cell fillWithVideo(video)

请注意,您似乎使用UIViewController,因此您可能需要添加UIViewController参数以使newIntitVideoPlayer()方法起作用,但我不想将其放入前面的例子让它更简单。您可能需要替换以下行:

cell fillWithVideo(video andViewController:self)

func fillWithVideo(videoParam video: CustomVideoClass andViewController viewController: UIViewController)
player?.newIntitVideoPlayer(forViewController: viewController, videoURL: video.postUrl, videoThumbnail: URL(string: video.thumbURL), onReady: nil)

等。对于每个部分特定部分。它使您更容易阅读您正在做的事情。仅在collectionView:cellForRowAtIndexPath:逻辑中处理(哪个部分应该获得哪个项目等),其余部分处理可能适应的单元格。