views:

385

answers:

4

Hello all! In my app, I have a table displaying a cell in each row. In Interface Builder, I dragged a button onto the cell, styled it as a Dark Info button, and connected it to a IBAction. That is working fine. Only, I want the button to behave differently, depending on the row of the table where the cell of the button is. How would I get that row index?

I realize that I might display a lack of basic understanding of the object hierarchy, but I hope you guys will forgive me

Thanks Sjakelien

A: 

In your tableView delegate and datasource methods (check the docs!) you have several methods, the best one for this is

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

Drop this method in your implementation and say something like

    switch (indexPath.row) {
     case 0:
//set variable or do method based on row 0 (first row)
      break;
     case 1:
//set variable or do method based on row 1 (second row)
      break;
     case 2:
//set variable or do method based on row 2 (third row)
      break;
    }//and so on
}
JoePasq
This happens when the cell is selected, not when a button within a cell is pushed. The OP said he had created and hooked up an IBAction, which is a separate method from any table view delegate/data source methods.
Tim
Yeah you're right tim. Maybe something like getting the cell when selected then it's view then that view's subview searching for the button.
JoePasq
+1  A: 

It's definitely not easy to do if you don't have some data set up first. If you can, have an NSDictionary where the buttons are the keys and the values are the index paths, that you update whenever you return a cell from -tableView:cellForRowAtIndexPath:. Something like this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ...
    [indexDict setValue:indexPath forKey:theButton];
    return cell;
}



- (void) buttonPressed:(UIButton *)button {
    NSIndexPath *indexPath = [indexDict valueForKey:button];
    ...
}
Ed Marty
+1  A: 

You can maintain tags. When you drag and drop the button, check the interface build and you will see "tag" property for these buttons. Assign different values for each of your button ( I assume you have different buttons for different rows, this solution will not work if you have same cell identifier for different rows ). And when you receive an event check for tag value. I had similar problem with my work and i was maintaing NSArray for each button tag created.

iamiPhone
A: 

another way is to change the base class of your UIButton in your view, then using this other class wich basically extends an UIButton with an added NSInteger row @property (remember to @synthesize it).

You'll then set this property during the cell setup, and you can retrieve this property within the message method

Lorenzo Boccaccia