如何从另一个函数触发UICollectionView的重载方法

时间:2016-05-16 08:30:38

标签: ios swift uicollectionview reload

我有一个UICollection视图,在我启动应用程序时加载就好了。我的问题是,当点击菜单栏中的按钮时,我需要用新数据重新加载它。这是我的代码。为了简单起见,我已经大大削减了它

    class RootViewController:  UIViewController,UICollectionViewDelegateFlowLayout, UICollectionViewDataSource{//The view controller that contains the collection view
        var carouselCollectionView: UICollectionView!//A reference to the collectionview
        override func viewDidLoad() {
            super.viewDidLoad()

            let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
            layout.sectionInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
            layout.itemSize = CGSize(width: carouselWindowWidth, height: carouselWindowHeight)
            layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
            layout.minimumInteritemSpacing = 5
            layout.minimumLineSpacing = 5

            carouselCollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
            carouselCollectionView.frame = CGRectMake(0,0,200,200)
            carouselCollectionView.delegate = self
            carouselCollectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
            carouselCollectionView.backgroundColor = UIColor.clearColor()

            self.view.addSubview(carouselCollectionView) //Add the collectionview to the main view(self)
        }//End viewDidLoad


        //Delegates for collectionViewController go here
        func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return currentImageArray.count
        }


        func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
            /*...*/
         }

         func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
             /*...*/
         }


         //This function is triggered when a menuItem on the menuBar is clicked.  It it supposed to fetch some data from some source, then reload the collectionview
        func reloadData(VC:UIViewController){
            /*...*/
            carouselCollectionView.reloadData()
        }

    }//End RootViewController

运行reloadData()时出现此错误

  

致命错误:在解包可选值时意外发现nil

有关如何正确执行此操作的任何想法?任何帮助非常感谢

PS。我在reloadData()

中运行viewDidLoad()时的预期数据

1 个答案:

答案 0 :(得分:-1)

好的你需要通过两个步骤处理这个问题:

  1. 创建一个集合视图的@IBOutlet,并将其与storyboard中的集合视图相关联:yourCollectionView

  2. 声明并初始化:var currentImageArray = UIImage

  3. 在按钮的@IBAction上:

  4. //做你的东西 //然后

    yourCollectionView.reloadData()

    让我知道它何时起作用!!!