Marshall Marshall - 3 months ago 34
Swift Question

ReloadData in UICollectionView

I use CoreData and want to reload the UICollectionView when I save a new entry in CoreData but the only

self.collectionview.reloaddata()
donĀ“t run it reload nothing.

Thanks for your Help.

My CoreData and UICollectionView I have try it to reload the UICollectionView when clockblogalarm become a new entry:

var clockblogalarm = [ClockBlogAlarm] () {
didSet { //self.ClockCollectionView.reloadData()
}
}


var mgdContext = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext


func loadClockAlarms () {
let LoadRequestBlogAlarm: NSFetchRequest<ClockBlogAlarm> = ClockBlogAlarm.fetchRequest()
clockblogalarm = try! mgdContext.fetch(LoadRequestBlogAlarm as! NSFetchRequest<NSFetchRequestResult>) as! [ClockBlogAlarm]
}



@IBOutlet var ClockCollectionView: UICollectionView!


override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.loadClockAlarms()
}


Here I save the Entry in CoreData. When I click the Button Done
view.bottomButtonHandler{}
then I want to reload the data and show it in the UICollectionView with loadClockAlarms() .

else if index == 1 {

let view = AddClockView.instantiateFromNib()
let window = UIApplication.shared.delegate?.window!
view.closeButtonHandler = {[weak modal] in
modal?.closeWithLeansRandom()
return
}
view.bottomButtonHandler = {[weak modal] in
modal?.closeWithLeansRandom()

self.loadClockAlarms()


return
}

modal.show(modalView: view, inView: window!)

}






// MARK: UICollectionViewDataSource



override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return clockblogalarm.count
}



override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AlarmBlogCell", for: indexPath) as! AlarmBlogCell

cell.layer.cornerRadius = 8



let clockblogalarms = clockblogalarm[indexPath.row]


if clockblogalarms.lock == "ClockblogAlarm" {

cell.Title.text = clockblogalarms.title
cell.Time.text = "SSSSS"

}




return cell
}

Answer

Ensure the reloadData() is called in the main thread, as it is the UI-responsible action:

dispatch_async(dispatch_get_main_queue()) {
    self.ClockCollectionView.reloadData()
}