Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

ios - add entires from textfield to UITableView to automatically populate

This is the code I have so far. I am able to enter into the textfield and have it appear in the UITableView, but only after I reload the page and come back to it. I want for what I enter into the textfield and when I click 'add' for it to automatically appear in the UITableView.

@IBOutlet var itemTextField: UITextField!
@IBOutlet var table: UITableView!

var items: [String] = []

@IBAction func add(_ sender: Any) {
    let itemsObject = UserDefaults.standard.object(forKey: "items")

    var items:[String]

    if let tempItems = itemsObject as? [String] {
        items = tempItems
        items.append(itemTextField.text!)

        print(items)
    } else {
        items = [itemTextField.text!]
    }

    UserDefaults.standard.set(items, forKey: "items" )
    itemTextField.text = ""
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()

    return true
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return items.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")

    cell.textLabel?.text = items[indexPath.row]
    cell.textLabel?.font = UIFont(name: "Type02", size: 20)

    return cell
}

override func viewDidAppear(_ animated: Bool) {
    let itemsOBject = UserDefaults.standard.object(forKey: "items")

    if let tempItems = itemsOBject as? [String]{
        items = tempItems
    }

    table.reloadData()
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == UITableViewCellEditingStyle.delete {
        items.remove(at: indexPath.row)

        table.reloadData()

        UserDefaults.standard.set(items, forKey: "items")
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to tell the table view to reloadData() whenever the items array changes. So try adding table.reloadData() to the end of your add function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...