當我們在textField中鍵入內容並按下按鈕時,它將textField的內容保存到Nsuserdefaults中。在其他View Controller中,TableView讀取NSUserDefaults並僅顯示一個單元格。當我們回到第一個ViewController來在textField中輸入其他內容時,我們再次按下按鈕,我們只能再次得到tableVIew中的一個單元格。當我們在textField中輸入內容時,tableView如何顯示多個單元格?Swift NSUserDefaults TableView多個單元格
ViewController.swift
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
var defaults = NSUserDefaults.standardUserDefaults()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func add2(sender: UIButton) {
var connection = self.textField.text
defaults.setObject(connection, forKey: "text")
}
}
ViewController2.swift
class ViewController2: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var defaults = NSUserDefaults.standardUserDefaults()
var ourText = String()
var textArray:[String] = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.tableView.delegate = self
self.tableView.dataSource = self
ourText = defaults.stringForKey("text")!
textArray.append(ourText)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return textArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = textArray[indexPath.row]
return cell
}
}