如何在iOS中单击UIButton时将项目插入UITableView

我一直在用tableViews练习,但我不知道如何插入新项目,当一个button被点击。

这是我的:

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 

我认为这是一个简单的插入项目数组和重新加载数据,但它不起作用。

有人可以告诉我如何添加新的项目,当一个button被点击一个tableView?

非常感谢

你做得对,

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

是正确的方法。

请仔细检查variablestableView ,我看不到它的声明。

确保你有,

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

并正确地将tableView连接到.nib

你在正确的轨道上。 确保你正确设置你的委托和数据源,你的sockets连接到button。

编辑:也相当肯定你不能只是@“胡说”string到一个可变的数组。 尝试将文本初始化为NSString,然后将其作为指针传入。