Yomo Yomo - 1 year ago 88
iOS Question

Do something with selected rows in a UITableView, using an IBAction (Obj-C)

I'd like to be able to select one row or more, and with an IBAction do something.

Let's say I have four rows, A, B, C and D. If I select A and B, and press the button connected to that IBAction, something happens.

How do I go about this?


@implementation ViewController {

NSArray *names;


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section


return [names count];


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath


static NSString *tableIdentifier = @"tableCell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableIdentifier];

if (cell == nil) {

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableIdentifier];


cell.textLabel.text = [names objectAtIndex:indexPath.row];
return cell;


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

if ((indexPath.row == 0) && (indexPath.row == 2)) {

NSLog(@"John and James selected.");



- (void)viewDidLoad {

[super viewDidLoad];
// Initialize table data
names = [NSArray arrayWithObjects:@"John", @"Michael", @"Hannah", @"James", nil];



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

    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];

    if ([selectedCell accessoryType] == UITableViewCellAccessoryNone) {
        [selectedCell setAccessoryType:UITableViewCellAccessoryCheckmark];
        [selectedIndexes addObject:[NSNumber numberWithInt:indexPath.row]];
    } else {
        [selectedCell setAccessoryType:UITableViewCellAccessoryNone];
        [selectedIndexes removeObject:[NSNumber numberWithInt:indexPath.row]];

    [tableView deselectRowAtIndexPath:indexPath animated:NO];


This code will show tick mark on your selected row.

You also have to use an array that maps the checked cells and in cellForRowAtIndexPath you have to verify if the accessoryType should be checked or not.

Then on your button action you can do your code with selected rows.

Hope this helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download