Display an alert in a TableViewCell

0

I want to show an alert when I press a button that is in a tableviewcell and it gives me the following error:

  

'NSInvalidArgumentException', reason: 'Application tried to present modal view controller on itself. Presenting controller is.

This is my code:

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

    cell.nombreEntradaLBL.text = nombreConcierto[indexPath.row]
    cell.comprarEntradaIMG.image = UIImage(named: imagenes[indexPath.row])
    cell.fechaEntradasLBL.text = fechas[indexPath.row]
    cell.comprarBTN.addTarget(self, action: #selector(ComprarTableViewController.mostrarAlerta), for: .touchUpInside)

    return cell
}

@objc func mostrarAlerta(){
    let alerta = UIAlertController(title: "Compra satisfactoria", message: "Se han comprado su entrada/as", preferredStyle: .alert)
    alerta.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
    alerta.present(alerta,animated: true)
}
    
asked by znapback 14.12.2018 в 18:27
source

1 answer

1

Your problem, as the error says, is that in this line:

alerta.present(alerta,animated: true)

You are indicating that the ViewController called alert, present the Viewcontroller alert, obviously this can not be, the correct thing would be that the ViewController that contains the TableView is the one that presents the alert.

Assuming that the showAlert method belongs to the parent ViewController then it would be enough to present it in the following way:

present(alerta,animated: true)
    
answered by 14.12.2018 / 19:16
source