dynamically fill action sheet Swift 3

0

I am looking for a way to make a floating list (TableView inside AlertView) with data from a list of objects and that when I click on an element it gives me the reference to the selected object.

For this I am using an action sheet and a for loop as follows

@IBAction func btnVerLista_onClick(_ sender: Any) {
        let alertController = UIAlertController(title: "Action Sheet", message: "Lista de Superheroes", preferredStyle: .actionSheet)

        for item in arrSuperHeroes{

            let superbutton = UIAlertAction(title: (item as! SuperHeroe).nombre , style: .default, handler: { (action) -> Void in
                self.superSel = item as! SuperHeroe
                print(self.superSel.nombre)
        })
        alertController.addAction(superbutton)
        }

        self.navigationController!.present(alertController, animated: true, completion: nil)
    }

But I always have this error when executing the last line

  

fatal error: unexpectedly found nil while unwrapping an Optional value   (lldb)

Someone could help me with the idea of error or if there is another way to do what I need.

    
asked by Kevtho 01.06.2017 в 05:53
source

1 answer

1

The last line of the code looks like this:

self.navigationController!.present(alertController, animated: true, completion: nil)

More context would be missing but it gives the impression that the navigationController is effectively nil , so the error happens. However, it is not necessary to use navigationController to invoke the present method, in this particular case, you can do about self .

The complete code would look like this:

class ViewController: UIViewController {

    private var héroes = ["Spiderman", "Superman", "Batman", "Sam Fisher", "Pikolín"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func héroesPresionado(_ sender: UIButton) {
        let sheet = UIAlertController(title: "Héroes", message: "Selecciona un héroe", preferredStyle: .actionSheet)

        for héroe in self.héroes {
            sheet.addAction(UIAlertAction(title: héroe, style: .default, handler: { (action: UIAlertAction) in
                print("Seleccionaste a: \(héroe)")
            }))
        }

        self.present(sheet, animated: true) {
        }
    }
}

The application looks like this:

    
answered by 02.06.2017 / 20:23
source