【发布时间】:2017-12-24 23:16:28
【问题描述】:
我有一个字符串数组,它正在填充一个集合视图并且效果很好。问题是我想用保存在用户输入文本字段中的用户默认值中的字符串附加该数组。我正在获取 UserDefault 数据,问题是它没有显示在单独的集合视图单元格中。它附加在当前单元格中每个字符串的末尾。在此先感谢,任何帮助将不胜感激。
这是我迄今为止尝试过的:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
let defaults = UserDefaults.standard
let value = defaults.string(forKey: "Gratitude")
print(value!)
//Array that I am trying to append with userdefault data
gratitudeArray.append(value!)
// Configure the cell
cell.cellLabel.text = gratitudeArray[indexPath.row]
return cell
}
// 我正在从警报中获取用户输入并保存在 userdefaults 中,如下所示:
func presentAlert() { let alertController = UIAlertController(title: "", message: "Create your own Gratitude:", preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "Save", style: .default) { (_) in
if let field = alertController.textFields?[0] {
// store data
UserDefaults.standard.set(field.text, forKey: "Gratitude")
UserDefaults.standard.synchronize()
} else {
print()
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
alertController.addTextField { (textField) in
//print(textField.text!)
//textField.placeholder = ""
}
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
【问题讨论】:
-
这是因为您将
gratitudeArray元素附加到您已经定义用于将元素存储在collectionView中的同一单元格中 -
无论您从
UserDefaults获得什么,都做一件事,将其附加到您之前用于填充collectionView单元格的同一数组中 -
你想在单元格中显示什么? "gratitudeArray[indexPath.row] + value" 或 "gratitudeArray + value"
-
@ Samarth Kejriwal 感谢您的回复,这就是我想要做的,但它没有显示在集合视图的新单元格中。它正在连接到当前单元格的末尾
-
@JD 我想在单独的单元格中显示感谢和 userDefaults 的值
标签: arrays swift swift3 nsuserdefaults