从另一个视图类重新加载集合视图数据

我在视图中有两个容器。 顶部有一个收集视图。 我想从下面的容器点击button时更新我的​​集合视图。 我的button也正在改变我的集合视图使用的数组的值。

我以为didSet会做这项工作,但不幸的是没有工作。

最佳:

class TopViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { @IBOutlet weak var favoritesCV: UICollectionView! var myFavorites = [] { didSet { self.favoritesCV.reloadData() } } override func viewDidAppear(animated: Bool) { myFavorites = favoritesInstance.favoritesArray } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return myFavorites.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell : FavoritesCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! FavoritesCollectionViewCell var myPath = myFavorites[indexPath.row] as! String cell.myImage.image = UIImage(named: myPath) return cell } } 

底部:

 class BottomViewController: UIViewController, UIScrollViewDelegate { @IBAction func addFavorites(sender: AnyObject) { favoritesInstance.favoritesArray.append("aaaa.jpg") } } 

存储类别:

 class Favorites { var favoritesArray:Array <AnyObject> init(favoritesArray:Array <AnyObject>) { self.favoritesArray = favoritesArray } } var favoritesInstance = Favorites(favoritesArray:[]) 

我已经添加了

 NSNotificationCenter.defaultCenter().addObserver(self, selector: "loadList:", name:"load", object: nil) 

在我的collections查看类的viewdidload。 还增加了一个select器,当它被通知中心调用时重新加载我的数据

 func loadList(notification: NSNotification){ self.favoritesCV.reloadData() } 

对于按下button的另一个类:

 NSNotificationCenter.defaultCenter().postNotificationName("load", object: nil) 

Swift 3:

 NotificationCenter.default.addObserver(self, selector: #selector(loadList), name:NSNotification.Name(rawValue: "load"), object: nil) NotificationCenter.default.post(name: NSNotification.Name(rawValue: "load"), object: nil) 

大! 我在找这个 在Swift 3中,代码略有不同。 在collectionviewcontroller中:

 NotificationCenter.default.addObserver(self, selector: #selector(RoundCollectionViewController.load), name:NSNotification.Name(rawValue: "reload"), object: nil) 

另一个:

 NotificationCenter.default.post(name: NSNotification.Name(rawValue: "load"), object: nil)