Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert items to a UITableView when a UIButton is clicked in iOS

I have been practicing with tableViews but I cannot figure out how to insert new items when a button is clicked.

This is what I have:

BIDViewController.h:

#import <UIKit/UIKit.h>

@interface BIDViewController : UIViewController

// add protocols
<UITableViewDataSource, UITableViewDelegate>

//this will hold the data
@property (strong, nonatomic) NSMutableArray *names;

- (IBAction)addItems:(id)sender;

@end

BIDViewController.m:

#import "BIDViewController.h"

@interface BIDViewController ()

@end

@implementation BIDViewController

//lazy instantiation
-(NSMutableArray*)names
{
    if (_names == nil) {
        _names = [[NSMutableArray alloc]init];
    }
    return _names;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // add data to be display

    [self.names addObject:@"Daniel"];
    [self.names addObject:@"Alejandro"];
    [self.names addObject:@"Nathan"];
}

//table view
-(NSInteger)tableView:(UITableView*)tableView
numberOfRowsInSection:(NSInteger)section
{
    return [self.names count];
}

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

    UITableViewCell *cell =  [tableView dequeueReusableCellWithIdentifier:@"identifier"];

    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"identifier"];
    }
    cell.textLabel.text =  self.names [indexPath.row];
    return cell;
}

- (IBAction)addItems:(id)sender {
    // I thought it was as simple as this, but it doesn't work
    [self.names addObject:@"Brad"];
    [tableView relaodData];
}
@end

I thought it was a simple as inserting items to the array and than reloading the data but it doesn't work.

Can someone show me how to add new items to a tableView when a button is clicked?

Thanks a lot

like image 320
fs_tigre Avatar asked Jan 17 '26 05:01

fs_tigre


1 Answers

You are doing it right,

- (IBAction)addItems:(id)sender {
    // I thought it was as simple as this, but it doesn't work
    [self.names addObject:@"Brad"];
    [self.tableView relaodData];
}

is the correct way.

Please double check the variable tableView, I can't see the declaration of it.

make sure you have,

@property(weak, nonatomic) IBOutlet UITableView *tableView;
[self.tableView setDelegate:self];
[self.tableView setDataSource:self];

and properly connected the tableView to .nib

like image 148
Thilina Chamath Hewagama Avatar answered Jan 19 '26 20:01

Thilina Chamath Hewagama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!