I am new to swift and trying to implement collectionView function in a ViewController.Now I have three types of UICollectionViewCell,here is my code:
func co
You can try to assign each collectionView a unique tag like so
collectionView.tag = 1
and then use the tag as the identifier:
switch collectionView.tag {
case 0:
// some code
case 1:
// some code
default:
// some code
}
If you're using your collectionViews inside UITableViewCell
s you can set each collectionView.tag
to be indexPath.section
or indexPath.row
within tableView(_ tableView: willDisplay cell: forRowAt indexPath:)
.
Here's a nice subclass you could use:
class CollectionViewTableViewCell: UITableViewCell {
@IBOutlet weak var collectionView: UICollectionView!
func setCollectionViewDataSourceDelegate(dataSource: UICollectionViewDataSource?, dataDelegate: UICollectionViewDelegate?, forSection section: Int) {
collectionView.delegate = dataSource as! UICollectionViewDelegate?
collectionView.dataSource = dataDelegate as! UICollectionViewDataSource?
collectionView.tag = section
collectionView.reloadData()
}
}
and then in your view controller implement
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let tableViewCell = cell as? CollectionViewTableViewCell else { return }
tableViewCell.setCollectionViewDataSourceDelegate(dataSource: self, dataDelegate: self, forSection: indexPath.section)
}
Hope this help. Not testing at all. If any issues, can you take a snip ?
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:UICollectionViewCell
switch collectionView {
case self.collectionViewCategory:
let categoryCell = collectionView.dequeueReusableCell(withReuseIdentifier: categoryIdentifier, for: indexPath as IndexPath) as! CategoryCell
categoryCell.CategoryIcon.image = self.categoryItems[indexPath.item]
cell = categoryCell
case self.collectionViewHour:
let hourCell = collectionView.dequeueReusableCell(withReuseIdentifier: hourIdentifier, for: indexPath as IndexPath) as! HourCell
hourCell.hourItem.text = self.hourItems[indexPath.item]
cell = hourCell
default:
//do nothing.
}
cell.layer.borderColor = UIColor.lightGray.cgColor
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 5
return cell
}