PaulW
PaulW

Reputation: 23

Passing data from a textfield in a custom cell to the tableview in Swift

I have a TableView Controller with 2 types of cell. In the first row i have a custom cell that contains a text field and a button. In the remaining rows i have standard cells just showing strings from an array of Items (simple model; just title:String for the moment).

When I push the button in the first cell i want the text in the text field to be added as a row in the table view.

I have setup a protocol/delegate between the tableview and the custom cell. When the button is pushed it should pass the Item from the custom cell class to the view controller.

I have add 2 print statements and only the one on the button (Button Pushed) is printed. For some reason the View Controller is not firing, what am i doing wrong?

The cell...

protocol addItemDelegate {
    func didAddANewItem(with: Item)
}

class AddTableViewCell: UITableViewCell {

    @IBOutlet weak var addItemTextField: UITextField!
    
    var delegate: addItemDelegate?
    
    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
    @IBAction func addItemButton(_ sender: UIButton) {        
        print("Button Pushed")
        if let newItemTitle = addItemTextField.text {
            let newItem = Item(title: newItemTitle)
            delegate?.didAddANewItem(with: newItem)
        }
    }
}

The View Controller

class ItemViewController: UITableViewController, addItemDelegate {

    var items = [Item]()
    
    var addItemTableViewCell = AddTableViewCell()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        addItemTableViewCell.delegate = self
        
        tableView.register(UINib(nibName: "AddTableViewCell", bundle: nil), forCellReuseIdentifier: "addCell")

        let newItem1 = Item(title: "Apple")
        let newItem2 = Item(title: "Pear")
        let newItem3 = Item(title: "Orange")
        items.append(newItem1)
        items.append(newItem2)
        items.append(newItem3)
    }
    
    func didAddANewItem(with itemToAdd: Item){
        print("Delegate fired")
        items.append(itemToAdd)
        tableView.reloadData()
    }

Upvotes: 0

Views: 19

Answers (0)

Related Questions