Igor Tupitsyn
Igor Tupitsyn

Reputation: 1193

Selecting first row in UITableViewController in Swift

I am trying to select the first row in the UITableViewController once it appears (through a segue).

I am using the following code which I inherited from my previous Objective C project:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let customCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! IGANavlistTableCustomViewCell

        // Code that sets the custom view cell

        // Then...
        // Selecting the first row by default
        if(indexPath.row == 0)
        {
            let rowToSelect:NSIndexPath = NSIndexPath(forRow: 0, inSection: 0)

            tableView.selectRowAtIndexPath(rowToSelect, animated: true, scrollPosition: UITableViewScrollPosition.None)

            tableView.delegate?.tableView!(tableView, didSelectRowAtIndexPath: rowToSelect)
        }

        return customCell;
    }

I receive the following error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[IGANavlistTableVC tableView:didSelectRowAtIndexPath:]: unrecognized selector sent to instance 0x79e21040'

I would appreciate if someone could help.

Thank you!

EDIT:

This is my didDeselectRowAtIndexPath method:

var navaidSelected = [String]()
var listOfNavPoints = [[String]]()

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath)
    {
        // The selected object of the Array with all navaids data (i.e., the selected navaid) is converted to a string
        self.navaidSelected = self.listOfNavPoints[indexPath.row]
    }

Upvotes: 0

Views: 5347

Answers (1)

t4nhpt
t4nhpt

Reputation: 5302

You forgot implement func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) method.

And you needn't to use delegate when call didSelectRowAtIndexPath:

if(indexPath.row == 0)
        {
            let rowToSelect:NSIndexPath = NSIndexPath(forRow: 0, inSection: 0)

            tableView.selectRowAtIndexPath(rowToSelect, animated: true, scrollPosition: UITableViewScrollPosition.None)

           self.tableView(tableView, didSelectRowAtIndexPath: rowToSelect)
        }

=== EDITED ===

Change your didDeselectRowAtIndexPath to didSelectRowAtIndexPath.

Upvotes: 4

Related Questions