简体   繁体   中英

Add new cell in tableView from textfield

I created a table and a text field. I want the table to create a new cell every time the user writes something in the text box.I have a code like this. I created an array for names and try to fill cells with it, but so far there is no result.

var playerName = [String]()
    @IBAction func addPlayerNameTextFieldAction(_ sender:UITextField)
    {

        let name = addplayerTextFiedOutlet.text!
        playerName.append(name)

        addplayerTextFiedOutlet.resignFirstResponder()
        playerListTableView.reloadData()
    }




func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = playerListTableView.dequeueReusableCell(withIdentifier: idCell, for:indexPath) as! PlayerListTableViewCell
            cell.playerNameLabel.text =  playerName[indexPath.row]

        return cell
}

If you want to perform your action when press return key on the keyboard you should implement the UITextfieldDelegate method and set keyboard delegate to your controller and do stuff in this method

in your viewDidLoad method :

textfield.delegate = self

then impelement delegation method:

extension YourviewController: UITextFieldDelegate {

func textFieldShouldReturn(_ textField: UITextField) -> Bool {   //delegate method
   let name = addplayerTextFiedOutlet.text!
        playerName.append(name)
        addplayerTextFiedOutlet.resignFirstResponder()
        playerListTableView.reloadData()
        return true
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM