开发者

How to find the row index of a UIButton is a TableCell? (iPhone)

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


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];
    ...
}


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.


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
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜