我有一个字符串数组,它正在填充 Collection View 并且效果很好。问题是我想在该数组中附加保存在用户输入文本字段的用户默认值中的字符串。我正在获取 UserDefault 数据,问题是它没有显示在单独的 Collection View 单元格中。它附加在当前单元格中每个字符串的末尾。预先感谢,任何帮助将不胜感激。
这是我到目前为止尝试过的:
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
}
//我从警报中获取用户输入并保存在用户默认值中,如下所示:
func presentAlert() { letalertController = UIAlertController(title: "", message: "创建你自己的 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()
} khác {
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)
}
将字符串存储在 ViewDidLoad() 中,如下所示:
var strValue: String = ""
override func viewDidLoad() {
super.viewDidLoad()
let defaults = UserDefaults.standard
strValue= defaults.string(forKey: "Gratitude")
}
并在 cellForItemAt 中显示如下:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
cell.cellLabel.text = gratitudeArray[indexPath.row] + " " + strValue
return cell
}
Tôi là một lập trình viên xuất sắc, rất giỏi!