sách gpt4 ăn đã đi

arrays - 使用 UserDefaults 输入文本追加数组

In lại Tác giả: Walker 123 更新时间:2023-11-30 12:17:46 25 4
mua khóa gpt4 giày nike

我有一个字符串数组,它正在填充 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)
}

câu trả lời hay nhất

将字符串存储在 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
}

关于arrays - 使用 UserDefaults 输入文本追加数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45194702/

25 4 0
Walker 123
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress