我有一个字符串数组,它填充了一个集合视图,效果很好 . 问题是我想要使用从用户输入文本字段保存在用户默认值中的字符串附加该数组 . 我收到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:“创建你自己的感激之情:”,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)
}
3 回答
在ViewDidLoad()中存储字符串,如下所示:
并在cellForItemAt中显示如下:
如果我正确理解您的问题,您需要将单元格数量增加一个(从UserDefaults中提取的值) . 为此,您应该将它附加到集合视图的数据源方法之外的某个位置(如viewDidLoad()),然后重新加载集合视图 .
我通过在警报控制器中创建一个数组来保存用户输入,然后将该数组保存到用户默认值,从而解决了这个问题 .
func presentAlert(){let alertController = UIAlertController(title:“”,message:“创建你自己的感激之情:”,preferredStyle:.alert)