I have an app which uses collection view to fetch array of data.
I have added a button to the collection view cell via storyboard.. When the user clicks on the button its selected state changes. Which is working fine.
Then I tried to save and retrieve the bool value of the UIButton for key "isSelected" using NSUserDefaults.
This is how i change the bool value and save using NSUserDefault.
@IBAction func likeBtn(_ sender: UIButton) {
if sender.isSelected == false {
sender.isSelected = true
let defaults = UserDefaults.standard
defaults.set(true, forKey: "isSelected")
}
else {
sender.isSelected = false
let defaults = UserDefaults.standard
defaults.set(false, forKey: "isSelected")
}
}
And at my cellForItemAt indexPath i tried fetching the bool value for the UIButton..
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = newsfeedColView.dequeueReusableCell(withReuseIdentifier: "NewsFeed", for: indexPath) as! NewsFeedCollectionViewCell
cell.likeBtn.addTarget(self, action: #selector(NewsFeedViewController.likeBtn(_:)), for: UIControlEvents.touchUpInside)
var defaults = UserDefaults.standard
var state = defaults.bool(forKey: "isSelected")
cell.likeBtn.isSelected = state
return cell
}
Everything works fine till i am using the app, but when i quit the app and open again, the saved bool value is assigned to the UIButton in each cell rather than just on the cell which I selected earlier using the app.
I think i have to specify the index path while saving using NSUserDefault. But can't figure out how as i am new to swift and Xcode.. Any help as how to go ahead .
Screen Shot of the viewcontroller
Any help...Been suck here for a longtime.. Cant figure out the way to tackle this situation... Please ..