gpt4 book ai didi

ios - 在 Collection View Cell 中实现类似按钮

转载 作者:行者123 更新时间:2023-11-28 08:22:24 24 4
gpt4 key购买 nike

我有一个使用 Collection View 来获取数据数组的应用。

我已经通过 Storyboard向 Collection View 单元格添加了一个按钮。当用户单击该按钮时,其选定状态会发生变化。哪个工作正常。

然后我尝试使用 NSUserDefaults 保存和检索键“isSelected”的 UIButton 的 bool 值。

这就是我使用 NSUserDefault 更改 bool 值并保存的方式。

@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 保存时指定索引路径。但无法弄清楚我是 swift 和 Xcode 的新手。关于如何继续的任何帮助。

Screen Shot of the viewcontroller

任何帮助...在这里被吸了很长时间..无法找到解决这种情况的方法...请..

最佳答案

因为您只是为所有 tableView 的行使用一个值,所以当您“选择”为真时,它将对所有现在发生的事情都为真。您确实需要数据库来为每一行保存那些“选定”状态。但是如果这只是一个原型(prototype),您可以使用 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
}

关于ios - 在 Collection View Cell 中实现类似按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40921021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com