2016-12-01 76 views
1

我有一個應用程序,它使用集合視圖來獲取數據數組。在集合視圖單元格中實現像按鈕

我已經通過故事板向集合視圖單元添加了一個按鈕。當用戶單擊按鈕時,其所選狀態發生更改。哪個工作正常。

然後我試着保存並檢索使用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

任何幫助......去過吸這裏的長期..不能想出應付這一局面的方式......請..

+0

1)你不需要做userdefaults來獲得這樣的效果。你仍然可以使用'likeBtn.isSelected'來引用'cellForItemAt'中的按鈕。2)你應該將'index.row'存儲在userdefaults中。3)該按鈕與viewController的視圖相關,它與* every *細胞。 – Honey

+0

我很抱歉,但我沒有得到你想暗示的? –

+0

哪部分? 1,2,3? – Honey

回答

0

當你只是用所有的一個值你的tableView的行,當你'選擇'是真的時候,對於現在正在發生的所有事情都是如此。 您確實需要數據庫來爲每一行保存這些「選定」狀態。 但是,如果這只是一個原型,你可以使用UserDefaults作爲你的快速數據庫。爲此,您需要爲每個'isSelected'行使用不同的鍵,並使用按鈕標籤作爲鍵。

@IBAction func likeBtn(_ sender: UIButton) 
{ 
    if sender.isSelected == false { 
    sender.isSelected = true 

    let defaults = UserDefaults.standard 
    defaults.set(true, forKey: "isSelected\(sender.tag)") 
    } 
    else { 
    sender.isSelected = false 
    let defaults = UserDefaults.standard 
    defaults.set(false, forKey: "isSelected\(sender.tag)") 
    } 
} 

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) 

    let tag = indexPath.row 
    cell.likeBtn.tag = tag 
    var defaults = UserDefaults.standard 
    var state = defaults.bool(forKey: "isSelected\(tag)") 

    cell.likeBtn.isSelected = state 

    return cell 
} 
+0

我試過這個解決方案,但是當單元格消失或者我重新啓動應用程序時,按鈕的選定狀態將重置爲默認狀態,即false。不能弄清楚我做錯了什麼。這是處理這個問題的正確方法嗎?或者我應該使用另一種方法。 –

+0

可以這樣做。如果不是如何去解決這個問題.. –

相關問題