LK Phuc Nguyen LK Phuc Nguyen - 6 months ago 6x
Swift Question

Selected row passes `nil` to detail view

I have a screen with

Table View
that shows all the reminders storing in the object
currentReminders: NSMutableArray

Now I am doing on tapping a row of reminder list leading to a screen to show its details.

What I want to do is: selecting a row, get row index, then pick the corresponding reminder object in the array at such row index to pass to the next view.

How can I do it? I am new to Swift. This is my tute practice task.


You are on the right track. When you tap a cell in a table that triggers a segue, the sender parameter to prepareForSegue is the cell. You can use the tableView outlet and the cell object to get the indexPath and use that to retrieve the data from the array.

class ReminderListController: UITableViewController, addReminderProtocol {

    // assuming that the following gets loaded somehow.
    var currentReminders = [Reminders]()
    var reminderToPass: Reminders?

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if segue.identifier == "showReminderSegue" {
            // convert sender to a cell
            if let cell = sender as? UITableViewCell {
                // get the indexPath of that cell in the tableView
                let indexPath = tableView.indexPathForCell(cell)
                if let destinationVC = segue.destinationViewController as? ShowReminderController {
                    destinationVC.aReminder = currentReminders[indexPath.row]