Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table view cell as button

I'm trying to set a Table View Cell that has been grouped, as a button however I can't seem to find where to do it in the interface builder in XCode 4.2 or programmatically.

I've tried linking the table view cell to an IBAction, however it only lets me create or link to an IBOutlet.

As a temporary fix I have embedded a rectangle button in the cell, but this doesn't highlight blue when pressed.

I've seen this work in several apps, an example is the Clear History and Clear Cookies and Data buttons in the Safari app below:

enter image description here

like image 450
jcrowson Avatar asked Dec 21 '22 01:12

jcrowson


1 Answers

Imagine that your IBAction is like this:

-(IBAction)buttonPressed{
//Do my stuff
}

Then, you should do this in your delegate:

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

    //check if your cell is pressed
    BOOL myCellIsPressed = ...

     if(myCellIsPressed)
        [self buttonPressed];
}

To check if your cell was pressed, you have several ways, for example, if you know the row of your button in the table:

int myCellRow = 5;
if (myCellRow == IndexPath.row) //YES!

Or you can put a tag in your cell and then check if is that one:

#define myTag 5

When creating the cell:

UITableViewCell *myCell = ...
myCell.tag = myTag

And in didSelectRowAtIndexPath:

UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
if (selectedCell.tag == myTag) //YES!
like image 115
Antonio MG Avatar answered Jan 05 '23 10:01

Antonio MG