Reload collection view data from another view class

前端 未结 3 975
一生所求
一生所求 2020-12-25 10:23

I have two containers in a view. The top one has a collection view. I want to update my collection view from a button when a button is hit from the below container. My butto

相关标签:
3条回答
  • 2020-12-25 10:42

    I have added

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

    in my viewdidload of my collection view class. also added a selector which reloads my data when it is called by the Notification Center

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

    and for the other class where the button is pressed:

    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)
    
    0 讨论(0)
  • 2020-12-25 10:48

    Great! I was looking for this. In Swift 3 the code is slightly different. In collectionviewcontroller:

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

    and in the other one:

    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "load"), object: nil)
    
    0 讨论(0)
  • 2020-12-25 10:54

    Swift 4:

    1st class:

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

    Class with collectionView:

    in viewDidLoad():

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

    and function:

    @objc func loadList(notification: NSNotification) {
      self.collectionView.reloadData()
    }
    
    0 讨论(0)
提交回复
热议问题