我正在制作我的第一个应用程序,它有一个任务管理器,为此,我创建了一个表格视图,您可以在其中通过警报输入“任务”。我怎样才能保存输入的“任务”?我做了一些研究,但是,我无法找到答案。 代码如下: (斯威夫特2)我做了一个表格视图,即使应用程序关闭后,我如何保存这些项目?
import UIKit
class ThirdViewController: UIViewController, UITableViewDataSource{
var items: [String] = []
@IBOutlet weak var listTableView: UITableView!
@IBAction func additem(sender: AnyObject) {
alert()
}
@IBAction func savebtn(sender: AnyObject) {
print (items)
}
override func viewDidLoad() {
super.viewDidLoad()
listTableView.dataSource = self
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("listitem") as! ItemTableViewCell
cell.itemLabel.text = items[indexPath.row]
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func alert() {
let alert = UIAlertController(title: "", message: "", preferredStyle: .Alert)
alert.addTextFieldWithConfigurationHandler{
(textfield) in
textfield.placeholder = "Enter your task"
}
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
print ("Hi")
}
alert.addAction(add)
alert.addAction(cancel)
presentViewController(alert, animated: true, completion: nil)
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
items.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
无关,但如果您刚刚开始使用Swift,为什么不使用Swift 3? Swift 2已经过时,不再支持。 – rmaddy
你的问题和你的解释没有同步。你说应用程序关闭后你想保存。但你解释说你不能在tableview中保存数据,哪一个是正确的? –
我建议你阅读关于核心数据并使用它;那么你的数据将被保存为“随你去” – Paulw11