在使用单独的数据源进行collectionView的同时重新加载数据?

时间:2018-07-27 22:03:02

标签: ios swift swift4

感谢您的任何帮助或建议。我需要单个ViewController的两个集合视图,所以我决定将其中一个与其类分开。这是到目前为止我得到的:

import UIKit

class HomeViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

public var homeView: HomeView?;
public let calendarCollectionViewDataSourceAndDelegate = CalendarCollectionViewDataSourceAndDelegate();

public var month = Cal.currentMonth!;
public var year = Cal.currentYear!;

override func viewDidLoad() {
    super.viewDidLoad();

    homeView = HomeView(self).load();
}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1;
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 5;
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TodoCell", for: indexPath);
    return cell;
}

public func switchToNextMonth() {
    if(self.month == 12) {
        self.month = 1;
        self.year = self.year + 1;
        calendarCollectionViewDataSourceAndDelegate.year = self.year;
    } else {
        self.month = self.month + 1;
    }
    calendarCollectionViewDataSourceAndDelegate.month = self.month;

    ****//NEED TO RELOAD DATA HERE! ****
}

public func switchToPreviousMonth() {
    if(self.month == 1) {
        self.month = 12;
        self.year = self.year - 1;
        calendarCollectionViewDataSourceAndDelegate.year = self.year;
    } else {
        self.month = self.month - 1;
    }
    calendarCollectionViewDataSourceAndDelegate.month = self.month;
    **** //NEED TO RELOAD DATA HERE! ****


}

class CalendarCollectionViewDataSourceAndDelegate : NSObject, UICollectionViewDataSource, UICollectionViewDelegate {

    //ALL THE CODE FOR THE SEPARATE COLLECTIONVIEW IS HERE!

}

它在初始数据上运行良好,但是如何重新加载数据并从那里反映更改?如果它符合UICollectionViewUIViewController,我可以这样做,但是如何为DataSource使用单独的类呢?

1 个答案:

答案 0 :(得分:1)

您必须以calendarCollectionViewDataSourceAndDelegate.collectionView.reloadData()的身份访问单独的collectionView,或者可以编写调用collectionView.reloadData()的方法,例如:

class CalendarCollectionViewDataSourceAndDelegate : NSObject, UICollectionViewDataSource, UICollectionViewDelegate {

   let collectionView: UICollectionView

   //Init method and other dataSource and delegate methods

   func reload() {
       self.collectionView.reloadData()
   }
}