每当用户按下按钮时,我都会尝试将某些东西添加到数组中,并将其另存为UserDefault。
我可以根据用户输入的内容将文本字段另存为用户默认值,但是我很难将其保存并附加到数组中。
import UIKit
var nums = ["3","4","5"]
class ViewController: UIViewController {
@IBOutlet weak var text: UITextField!
@IBAction func submit_button(_ sender: Any) {
UserDefaults.standard.set(text.text!, forKey: "Submitted")
// append
nums.append("\(String(describing: text))")
}
override func viewDidLoad() {
super.viewDidLoad()
let savedscore = UserDefaults.standard.object(forKey: "Submitted")
if let saving = savedscore as?
String{text.text = saving}
}
}
每当有人在文本字段中提交时,我都在尝试增加我的数组
答案 0 :(得分:0)
获取最后一个值
保存
let str = text.text!
UserDefaults.standard.set(str, forKey: "Submitted")
nums.append(str)
阅读
if let savedscore = UserDefaults.standard.string(forKey: "Submitted") {
self.text.text = savedscore
}
对于阵列
保存
let str = text.text!
nums.append(str)
UserDefaults.standard.set(nums, forKey: "Submitted")
阅读
if let arr = UserDefaults.standard.array(forKey: "Submitted") as? [String] {
print(arr)
// set first value or what you need
self.text.text = arr.first
}
答案 1 :(得分:0)
您可以在按钮操作中附加文本后保存数组
@IBAction func submit_button(_ sender: Any) {
UserDefaults.standard.set(text.text!, forKey: "Submitted")
// append
nums.append("\(String(describing: text.text!))")
UserDefaults.standard.set(nums, forKey: "nums")
}
要获取价值,请使用
if let nums = UserDefaults.standard.array(forKey: "nums") as? [String] {
print(nums)
}
或者您可以将计算属性与属性观察器一起使用,以在附加新值时自动将数组保存在UserDefaults中。
class ViewController: UIViewController {
var nums: [String] {
get {
return UserDefaults.standard.array(forKey: "arrayValue") as? [String] ?? []
}
set {
UserDefaults.standard.set(newValue, forKey: "arrayValue")
}
}
@IBOutlet weak var text: UITextField!
@IBAction func submit_button(_ sender: Any) {
nums.append(text.text!)//Array updated in UserDefaults automatically
}
override func viewDidLoad() {
super.viewDidLoad()
print(self.nums)//Array fetched from UserDefaults
}
}
答案 2 :(得分:0)
我已经改善了您的代码并解决了您的问题。因此,请继续检查以下代码,并在评论中分享您的评论。
import UIKit
class ViewController: UIViewController {
var nums = [String]()
@IBOutlet weak var textField: UITextField!
@IBAction func submit_button(_ sender: Any) {
if let text = textField.text {
// Append to array
nums.append("\(text)")
// Save to User Defaults
UserDefaults.standard.set(nums, forKey: "NumberOfArray")
UserDefaults.standard.set(textField.text, forKey: "Submitted")
// Refresh User Defaults
UserDefaults.standard.synchronize()
}
// Print Updated Data
print("numbers: \(nums)")
print("text: \(textField.text ?? "")")
}
override func viewDidLoad() {
super.viewDidLoad()
let savedscore = UserDefaults.standard.object(forKey: "Submitted")
if let saving = savedscore as? String
{
textField.text = saving
}
// Update Array Based on userdefault data.
nums = UserDefaults.standard.object(forKey: "NumberOfArray") as? [String] ?? []
// Print Saved Data
print("numbers: \(nums)")
print("text: \(textField.text ?? "")")
}
}