为collectionView使用单独的数据源时重新加载数据?

问题描述 投票:0回答:1

感谢您提前提供的任何帮助或建议。我需要为一个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!

}

它在初始数据上工作正常,但我如何重新加载数据并从那里反映我的视图的变化?如果它符合UICollectionViewor UIViewController我可以做到这一点,但我如何为DataSource单独的类做同样的事情?

ios swift swift4
1个回答
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()
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.