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

标签 ios swift swift4

提前感谢您的任何帮助或建议。我需要一个 ViewController 的两个 Collection View ,所以我决定将其中一个分离到它的类中。这是我到目前为止得到的:

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!

}

它在初始数据上运行良好,但我如何才能重新加载数据并从那里反射(reflect)我的 View 中的更改?如果它符合 UICollectionViewUIViewController 我可以做到这一点,但我如何对 DataSource 的单独类做同样的事情?

最佳答案

您必须以 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()
   }
}

关于ios - 在为 collectionView 使用单独的数据源时重新加载数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51566075/

相关文章:

ios - 如何在Xcode模拟器中设置特定的iOS版本?

ios - RTC(Rational Team Concert)与 XCode 集成

ios - 我如何根据用户的回答为常见问题创建模型?

iOS:自定义对象的 int 变量在 NSUserDefaults 中返回 nil

swift - 重叠访问 'urlComponents' ,但修改需要独占访问

swift - 代替可失败的初始化器,你可以让它返回一个默认情况吗?

iphone - 委托(delegate)和协议(protocol)无法正常工作

ios - 当应用程序一段时间不使用时调暗显示

swift - 使用协议(protocol)扩展在外部点击时关闭键盘

json - 将 JSON 结果读取为字典数组