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

前端 未结 2 647
伪装坚强ぢ
伪装坚强ぢ 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)
    }
    

提交回复
热议问题