【发布时间】:2016-12-01 21:49:09
【问题描述】:
我有一个应用程序,它使用集合视图来获取数据数组。
我通过情节提要向集合视图单元格添加了一个按钮。当用户单击该按钮时,其选定状态会发生变化。哪个工作正常。
然后我尝试使用 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 的布尔值..
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
}
在我使用该应用程序之前一切正常,但是当我退出应用程序并再次打开时,保存的布尔值将分配给每个单元格中的 UIButton,而不仅仅是我之前使用该应用程序选择的单元格。
我想我必须在使用 NSUserDefault 保存时指定索引路径。但无法弄清楚我是如何成为 swift 和 Xcode 的新手。任何关于如何继续的帮助。
Screen Shot of the viewcontroller
任何帮助...在这里吸了很长时间..无法弄清楚解决这种情况的方法...拜托..
【问题讨论】:
-
1) 你不需要做用户默认设置来实现这样的。您仍然可以使用
likeBtn.isSelected引用cellForItemAt中的按钮 2) 您应该将index.row存储在 userdefaults 中 3) 该按钮与 viewController 的视图相关,它与 every无关> 细胞。 -
对不起,我没听懂你的意思??
-
哪一部分? 1,2,3?
-
没有按钮与每个单元格相关。它不在视图中,而是在每个集合视图单元格中。
-
使用情节提要内的 viewController + button + collectionview 的屏幕截图更新您的问题。我可以更好地解释
标签: ios swift nsuserdefaults xcode8 collectionview