一个ViewController中多个tableView和collectionView协议实现方案

在一个ViewController中可能会存在多个tableView或者多个collectionView。那么当前ViewController在实现delegate的方法时候只能实现一次。


class MyViewController: UIViewController {
    let firstCollectionList = [AnyObject]()
    let firstCollectionView = UICollectionView(frame: CGRect(x:0, y:0,width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height), collectionViewLayout: UICollectionViewFlowLayout())
    let secondCollectionList = [AnyObject]()
    let secondCollectionView = UICollectionView(frame: CGRect(x:0, y:0,width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height), collectionViewLayout: UICollectionViewFlowLayout())

// 利用extension可以将一些方法和对协议的实现分开,让代码比较清楚
extension MyViewController: UICollectionViewDataSource, UICollectionViewDelegate{
      // 当要实现协议方法而面对不同的collectionView返回不同的值的时候
      func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 判断当前的这个collectionView是哪个,然后返回我们需要的值
        // 因为对象在swift中都是引用传递,所以这里传入进来collectionView是某个collectionView实例的指针,所以可以进行比较
        if(collectionView == self.firstCollectionView) {
            return firstCollectionList.count
        }
        return secondCollectionList.count
    }
   }
}

类似这个协议方法的实现,其他的亦然。

你可能感兴趣的:(一个ViewController中多个tableView和collectionView协议实现方案)