我正在製作我的第一個應用程序,它有一個任務管理器,爲此,我創建了一個表格視圖,您可以在其中通過警報輸入「任務」。我怎樣才能保存輸入的「任務」?我做了一些研究,但是,我無法找到答案。 代碼如下: (斯威夫特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