我正在xcode中为iOS创建一个简单的工作清单,尝试在切换选项卡时重新加载表视图时遇到问题。我已将其写入视图控制器:
override func viewDidAppear(_ animated: Bool) {
let itemsObject = UserDefaults.standard.object(forKey: "items")
if let tempItems = itemsObject as? NSMutableArray {
items = tempItems
}
table.reloadData()
}
我添加了如下表出口:
class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var table: UITableView!
所有项目均已使用UserDefaults正确地永久存储,当我重新启动应用程序时,会出现我要添加的新项目。但是我无法弄清楚为什么这种重载方法对我不起作用。
已添加完整代码:
第一个视图控制器:
import UIKit
class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var table: UITableView!
var items:NSMutableArray = []
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")
cell.textLabel?.text = items[indexPath.row] as? String
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
let itemsObject = UserDefaults.standard.object(forKey: "items")
if let tempItems = itemsObject as? NSMutableArray {
items = tempItems
}
table.reloadData()
}
}
第二个视图控制器:
import UIKit
class SecondViewController: UIViewController {
@IBOutlet weak var input: UITextField!
@IBAction func addItem(_ sender: Any) {
print(input.text!)
var items:[String]
let itemsObject = UserDefaults.standard.object(forKey: "items")
if let tempItems = itemsObject as? [String] {
items = tempItems
items.append(input.text!)
} else {
items = [input.text!]
}
UserDefaults.standard.set(items, forKey: "items")
input.text = ""
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}