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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With