Я тренировался с помощью tableViews, но не могу понять, как вставлять новые элементы при нажатии кнопки.Как вставлять элементы в UITableView при щелчке UIButton в iOS
Это то, что у меня есть:
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
Я думал, что это было просто, как вставки элементов в массив и чем перезарядка данные, но он не работает.
Может ли кто-нибудь показать мне, как добавлять новые элементы в таблицуView при нажатии кнопки?
Большое спасибо
Какое поведение вы в настоящее время наблюдаете? Вызывается ли 'addItems:' на самом деле? Я думаю, что вы тоже «reloadData». – jszumski