我的代码现在只列出了您手动输入的内容。但是,当用户切换视图控制器时,代码会消失。我试图使用userdefualts将当前代码保存在选择函数中的行数中,但它不会将项保存在tableview单元格中。我只是想保存在tableview单元格中的任何东西。UITableViewCell中的UserDefaults未保存(swift3)
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
var items: [String] = [""]
@IBOutlet weak var listTableView: UITableView!
@IBAction func addItem(_ sender: AnyObject) {
alert()
}
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
listTableView.dataSource = self
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "listitem") as! ItemTableViewCell
cell.itemLabel.text = items[indexPath.row]
cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = UIEdgeInsets.zero
cell.layoutMargins = UIEdgeInsets.zero
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let userDefaults = UserDefaults.standard
userDefaults.setValue(items, forKey: "items")
userDefaults.synchronize()
return items.count
}
func alert(){
let alert = UIAlertController(title: "", message: "", preferredStyle: .alert)
alert.addTextField{
(textfield) in
textfield.placeholder = " Enter "
}
let add = UIAlertAction(title: "Add", style: .default){
(action) in
let textfield = alert.textFields![0]
self.items.append(textfield.text!)
self.listTableView.reloadData()
}
let cancel = UIAlertAction(title: "Cancel", style: .cancel) {
(alert) in
}
alert.addAction(add)
alert.addAction(cancel)
present(alert, animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
items.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
}}
当用户切换视图控制器时,代码消失是什么意思? 'numberOfRowsInSection'曾经被调用过吗? – Ryan
'items'的类型是什么?如果它是一个自定义对象,则不能将它们存储在'UserDefaults'中。 – Ryan
@Ryan当用户转到主页然后转到列表页面。所有写在列表页面上的东西在退货时都不见了。 –