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

Kor*_*and 7 collections view ios swift

我在视图中有两个容器.顶部有一个集合视图.我想从下面的容器中点击按钮时从按钮更新我的集合视图.我的按钮也改变了我的集合视图使用的数组的值.

我以为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
    }
 }
Run Code Online (Sandbox Code Playgroud)

底部:

class BottomViewController: UIViewController, UIScrollViewDelegate  {

    @IBAction func addFavorites(sender: AnyObject) {
         favoritesInstance.favoritesArray.append("aaaa.jpg")
    }
}
Run Code Online (Sandbox Code Playgroud)

存储类:

class Favorites {
    var favoritesArray:Array <AnyObject>

    init(favoritesArray:Array <AnyObject>) {
        self.favoritesArray = favoritesArray
    }
}

var favoritesInstance = Favorites(favoritesArray:[])
Run Code Online (Sandbox Code Playgroud)

Kor*_*and 8

我已经添加了

NSNotificationCenter.defaultCenter().addObserver(self, selector: "loadList:", name:"load", object: nil)
Run Code Online (Sandbox Code Playgroud)

在我的集合视图类的viewdidload中.还添加了一个选择器,在通知中心调用数据时重新加载我的数据

func loadList(notification: NSNotification){
    self.favoritesCV.reloadData()
}
Run Code Online (Sandbox Code Playgroud)

对于按下按钮的其他类:

NSNotificationCenter.defaultCenter().postNotificationName("load", object: nil)
Run Code Online (Sandbox Code Playgroud)

斯威夫特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)
Run Code Online (Sandbox Code Playgroud)


Bog*_*kiy 5

斯威夫特4:

一等舱:

NotificationCenter.default.post(name: NSNotification.Name("load"), object: nil)
Run Code Online (Sandbox Code Playgroud)

具有collectionView的类:

在viewDidLoad()中:

NotificationCenter.default.addObserver(self, selector: #selector(loadList(notification:)), name: NSNotification.Name(rawValue: "load"), object: nil)
Run Code Online (Sandbox Code Playgroud)

和功能:

@objc func loadList(notification: NSNotification) {
  self.collectionView.reloadData()
}
Run Code Online (Sandbox Code Playgroud)