I created a note app. The NotizenViewControllerArchive
save the note and with the NotizenViewControllerAdd
can you add new notes.
There is a third Viewcontroller, on this I can visit the other two views, but after I switched (with a button) from the third Viewcontroller to NotizenViewControllerArchive
there is a time delay, a short moment who I can't see my notes how can I fix that so the notes shows immediately?.
I tried for a long time to fix it but I don't know how, I put the whole code in because I don't know where the problem is. Thanks for your help
NotizenViewControllerArchive
import UIKit
class NotizenViewControllerArchive: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var table: UITableView!
var items:[String] = []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "Cell")
let backgroundView = UIView()
backgroundView.backgroundColor = UIColor.init(red: 48/255, green: 173/255, blue: 99/255, alpha: 1)
cell.selectedBackgroundView = backgroundView
cell.textLabel?.text = items[indexPath.row]
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
let itemObject = UserDefaults.standard.object(forKey: "items")
if let tempItems = itemObject as? [String] {
items = tempItems
}
table.reloadData()
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCell.EditingStyle.delete {
items.remove(at: indexPath.row)
tableView.reloadData()
UserDefaults.standard.set(items, forKey: "items")
}
}
}
NotizenViewControllerAdd
import UIKit
class NotizenViewControllerAdd: UIViewController, UITextFieldDelegate {
@IBOutlet weak var itemTextField: UITextField!
@IBAction func ad(_ sender: UIButton) {
let itemObject = UserDefaults.standard.object(forKey: "items")
var items:[String]
if let tempItems = itemObject as? [String] {
items = tempItems
items.append(itemTextField.text!)
print("items")
} else {
items = [itemTextField.text!]
}
UserDefaults.standard.set(items, forKey: "items")
itemTextField.text = ""
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
Try moving the code from viewDidAppear to viewWillAppear or viewDidLoad on your NotizenViewControllerArchive. The code inside the viewDidAppear will only execute after the view is already on screen for the user (hence the name)