Today we will learn how to put default checkbox in tableview in iOS. By the end of this post we will have output something like this.

Screen Shot 2016-07-28 at 9.52.57 PM

Steps:

  1. Create a new Xcode Project Lets say (DefaultCheckBoxTableView).
  2. Now in Your storybaord take a tableview and a label and connect the tableview delegate.

Screen Shot 2016-07-28 at 9.55.10 PM.png

Adding tableView delegates

Screen Shot 2016-07-28 at 9.58.18 PM.png

  1. Now make IBoutlet connection for the tableView.

  2. Then write the tableviewDelegates and datasource methods. Your ViewController.m will look something like this.

#import “ViewController.h”

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong,nonatomic) NSMutableArray *tableArray;

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    self.tableArray = [[NSMutableArray alloc]initWithObjects:@”Ram”,@”Shyam”,@”GhanShyam”, nil];

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

#pragma mark – tableView delegates  Methods

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    

    return [self.tableArray count];

}

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    

    static NSString *simpleTableIdentifier = @”SimpleTableItem”;

    

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    

    if (cell == nil) {

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

    }

    

    cell.textLabel.text = [self.tableArray objectAtIndex:indexPath.row];

   [_tableView setEditing:YES animated:YES];

    return cell;

}

#pragma mark – UITableView Delegate Methods

– (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return 3;

}

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

{

    NSLog(@”You have selected %@”,[self.tableArray objectAtIndex:indexPath.row]);

}

– (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath

{

    NSLog(@”You haver deselected %@”,[self.tableArray objectAtIndex:indexPath.row]);

}

@end

5. Run the code and see the desired output.

You can download the whole source code from  here.  Please have your valuable feedback.

Enjoy Coding. 🙂

Advertisements