Search code examples
iosswiftuitableviewcustom-cell

Can't get the textfield text in tableview custom cell


I am new to iOS and I am trying to build an app. In the app I wrote a tableview and this table has custom cells containing an image and textfield. User enters names in textfields (like player names), then I need to pass these names to another view controller. I am trying to get these names but I can't. Can anyone help me for this problem? Here is my code:

In tableview controller class:

var playerCount : Int = 0
var playerNumber = 0
var tempPlayers: [Player] = []

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellForPlayer", for: indexPath) as! PlayerInformationCellTableViewCell

    cell.txtPlayerName.placeholder = "Oyuncu \(playerNumber + 1)"
    playerNumber = playerNumber + 1
    cell.textFieldDidEndEditing(cell.txtPlayerName)
    tempPlayers.append(cell.tmpPlyer)
    return cell
}

Custom cell class:

var playerNames: [Player] = []
var tmpPlyer = Player(name:"",point: 0)

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
    txtPlayerName.delegate = self
    usrImgView.image = #imageLiteral(resourceName: "avatar")
    txtPlayerName.backgroundColor = UIColor.flatWhite
    txtPlayerName.layer.cornerRadius = 5
    txtPlayerName.textAlignment = .center
}

func textFieldDidEndEditing(_ textField: UITextField) {
    if(txtPlayerName.text != nil ){
       // var tempPlayer = Player(name: txtPlayerName.text!,point: 0)
        //playerNames.append(tempPlayer)
        tmpPlyer = Player(name: txtPlayerName.text!,point: 0)
    }
}

I am trying to get text with the didEndEditing method but I am open to suggestions.


Solution

  • You need to use Protocol and delegation pattern. In this pattern, you pass back your data from tableviewcell to view controller.

    Have a look at this tutorial

    https://medium.com/@aapierce0/swift-using-protocols-to-add-custom-behavior-to-a-uitableviewcell-2c1f09610aa1