How can I use switch statement to implement collectionView function in Swift?

前端 未结 2 633
伪装坚强ぢ
伪装坚强ぢ 2021-01-16 20:30

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         


        
相关标签:
2条回答
  • 2021-01-16 20:59

    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 UITableViewCells 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)
    }
    
    0 讨论(0)
  • 2021-01-16 21:19

    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
    

    }

    0 讨论(0)
提交回复
热议问题