Search code examples
iosiphoneswiftxcode6ios9

Having an issue grabbing the index of selected viewtable in swift


I have been learning swift through the last few days and I have come across an error that I have been stuck on for quite a while now.

I am attempting to get the selected indexPath so that I can then push data according to which item he selected. I have searched through and tried many different solutions I have found on stack overflow as well as different websites but I am not able to get this figured out still.

The code is below:

@IBOutlet var selectGroceryTable: UITableView!

/* Get size of table */
func tableView(tableView: UITableView, numberOfRowsInSection: Int) ->Int
{
    return grocery.count;
}
/* Fill the rows with data */
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let myCell:UITableViewCell = selectGroceryTable.dequeueReusableCellWithIdentifier("groceryListRow", forIndexPath:indexPath) as! UITableViewCell
    myCell.textLabel?.text = grocery[indexPath.row];
    myCell.imageView?.image = UIImage(named: groceryImage[indexPath.row]);
    return myCell;
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
    print("Row Selected");
    NSLog("Row Selected");
}

Nothing ever prints acting like the function is not being called. However, I do not understand why this would not be called?

Any help would be greatly appreciated!

UPDATE:

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

    selectGroceryTable.data = self;
    selectGroceryTable.delegate = self; //gives error states you can not do this

 }

Solution

  • There are a couple of things to check in cases like this:

    First, what kind of method is didSelectRowAtIndexPath?

    Answer: It's a UITableViewDelegate method. Did you set your view controller up as the delegate of the table view? If not, this method won't get called.

    Second, have you made absolutely certain that the method signature is a perfect match for the method from the protocol? A single letter out of place, the wrong upper/lower case, a wrong parameter, and it is a different method, and won't be called. it pays to copy the method signature right out of the protocol header file and then fill in the body to avoid minor typos with delegate methods.

    It looks to me like your method signature is correct, so my money is on forgetting to set your view controller up as the table view's delegate.