I need a UICollection view to show 1 of 2 sets of data upon selection. I'd like to use a segmented control but could use separate buttons as well. How do I configure the view controller to show the selected collection or implement 2 data sources in one collection view and implement switch?
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
switch control.selectedSegmentIndex {
case 0 :
guard let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: PhotoCollectionViewCell.identifier,
for: indexPath
) as? PhotoCollectionViewCell else {
fatalError()
}
cell.configure(with: URL(string: posts[indexPath.row].postUrlString))
return cell
case 1:
guard let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: VideoCollectionViewCell.identifier,
for: indexPath
) as? VideoCollectionViewCell else {
fatalError()
}
cell.configure(with: URL(string: posts[indexPath.row].postUrlString))
return cell
default:
guard let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: PhotoCollectionViewCell.identifier,
for: indexPath
) as? PhotoCollectionViewCell else {
fatalError()
}
cell.configure(with: URL(string: posts[indexPath.row].postUrlString))
return cell
}
}
@objc private func controlTapped(_ sender: UISegmentedControl) {
switch control.selectedSegmentIndex {
case 0:
collectionView?.reloadData()
return
case 1:
collectionView?.reloadData()
return
default:
collectionView?.reloadData()
}
}
EDIT:
I've edited the cellForItemAt
function as instructed.