Home > Blockchain >  How to append elements into an array from another View Controller in Swift
How to append elements into an array from another View Controller in Swift

Time:03-26

Hello guys I have a question about append a new element into an array everytime i pressed a button. I have two View Controllers, the first one "RegisterViewController", that contains a textfield and a button.

@IBAction func didTapSave(_ sender: UIButton) {
    usernameText.endEditing(true)
    userText = usernameText.text ?? ""
    performSegue(withIdentifier: "goToData", sender: self)    
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToData" {
        let destinationVC = segue.destination as! UserTableViewController
        destinationVC.userData = userText
        destinationVC.saveItems()
}

The idea is to add the texfield.text to a tableView that is in the SecondViewcontroller

by far I can append one textfield.text, then when I go back to RegisterViewController and try again with a different text, the array that i use for the tableView just "edits" that last string but doesnt add another element.

When i print the itemArray.count it's always 0 that means there's only one text, but doesnt add the other ones if i continue writing on the textfield

class UserTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 
    var userData : String?
    var itemArray = [Item]()
    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        saveItems()
    }
    func saveItems() {
        let newItem = Item(userRegister: userData ?? "")
        itemArray.append(newItem)
        print(itemArray.count)
        tableView.reloadData()
    }
}

CodePudding user response:

The reason there is that every time you load the UserTableViewController you are creating a new itemArray. The easiest way to solve this issue is to make RegisterViewController your table view data source and delegate. You just need to pass the register view controller instance to your tableview instead of passing the userData. Try like this:

class RegisterViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet weak var usernameText: UITextField!
    var items: [Item] = []
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        items.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath)
        var content = cell.defaultContentConfiguration()
        content.text = items[indexPath.row].userRegister
        cell.contentConfiguration = content
        return cell
    }
    @IBAction func didTapSave(_ sender: Any) {
        usernameText.endEditing(true)
        items.append(.init(userRegister: usernameText.text!))
        performSegue(withIdentifier: "goToData", sender: self)
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goToData" {
            let destinationVC = segue.destination as! UserTableViewController
            destinationVC.registerViewController = self
        }
    }
}

And your UserTableViewController:

class UserTableViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    var registerViewController: RegisterViewController?
    override func viewDidLoad() {
        super.viewDidLoad()   
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellID")
        tableView.delegate = registerViewController
        tableView.dataSource = registerViewController
    }
}
  • Related