我有一個應用程序,它使用集合視圖來獲取數據數組。在集合視圖單元格中實現像按鈕
我已經通過故事板向集合視圖單元添加了一個按鈕。當用戶單擊按鈕時,其所選狀態發生更改。哪個工作正常。
然後我試着保存並檢索使用NSUserDefaults的鍵「isSelected」的UIButton的布爾值。
這是我如何改變布爾值並保存使用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")
}
}
而且在我cellForItemAt indexPath我嘗試了UIButton的取bool值..
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
}
一切正常,直到我現在用的應用程序,但是當我再次退出應用程序和開放,保存的bool值被分配給每個單元格中的UIButton,而不僅僅是我之前使用應用程序選擇的單元格。
我想我必須在使用NSUserDefault進行保存時指定索引路徑。但無法弄清楚,因爲我是新的迅速和Xcode ..任何幫助,如何繼續前進。
Screen Shot of the viewcontroller
任何幫助......去過吸這裏的長期..不能想出應付這一局面的方式......請..
1)你不需要做userdefaults來獲得這樣的效果。你仍然可以使用'likeBtn.isSelected'來引用'cellForItemAt'中的按鈕。2)你應該將'index.row'存儲在userdefaults中。3)該按鈕與viewController的視圖相關,它與* every *細胞。 – Honey
我很抱歉,但我沒有得到你想暗示的? –
哪部分? 1,2,3? – Honey