У меня проблема, когда я использую представление коллекции с сегментомView.Вид коллекции с повторяющимися сегментами сегментов
У меня есть viewController
, который имеет segmentView с 4-х элементов (0 => Все, 1 => Фото, 2 => Audios, 3 => видео) вот и пример:
И у меня есть один 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
эти 2 фотографии показывают проблему
Отображение всех аудиозаписей ячейки, когда я нажимаю в аудио segmnet
Но после того, как я нажимаю на ячейки изображения или видео сегмента дублируется как это
это происходит в аудио - изображения - только видео ** (userProfileImageCollectionViewCell) **
и fin союзник вот мой userProfileImageCollectionViewCell код:
updateded:
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() })
}
}
В 'userProfileImageCollectionViewCell' в' prepareForReuse() 'сбросьте все значения (особенно те, которые могут присутствовать в одном случае и не присутствуют в другом). Иначе вы можете сделать это 'tableView: cellForRowAtIndexPath()', но поскольку у вас есть пользовательский файл для вашей ячейки, я бы рекомендовал сделать это в 'prepareForReuse()'. – Larme
'collectionView.reloadData()' в вашем элементе segmentedController должно помочь вам. – Moriya
Используйте только 'else' вместо' else if segmentStatues == 2' для последнего условия. –