正文:
利用 UserDefault 儲存資料
預覽圖:
程式碼:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var showLabel: UILabel!
@IBOutlet weak var enterTextField: UITextField!
var myUserDefaults :UserDefaults!
override func viewDidLoad() {
super.viewDidLoad()
myUserDefaults = UserDefaults.standard
}
@IBAction func updateButton() {
print("update Label")
// 結束編輯 把鍵盤隱藏起來
self.view.endEditing(true)
myUserDefaults.set(
enterTextField.text, forKey: "Label")
myUserDefaults.synchronize()
if let info = myUserDefaults.object(forKey: "Label") as? String {
showLabel.text = info
showLabel.textColor = UIColor.black
} else {
showLabel.text = "尚未儲存資訊"
showLabel.textColor = UIColor.black
}
}
@IBAction func removeButton() {
print("remove Label")
myUserDefaults.removeObject(forKey: "Label")
enterTextField.text = ""
if let info = myUserDefaults.object(forKey: "Label") as? String {
showLabel.text = info
} else {
showLabel.text = "尚未儲存資訊"
showLabel.textColor = UIColor.red
}
}
}