如何在iOS中当UIButton被点击时插入项目到UITableView



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

这是我的:

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

我认为这是一个简单的插入项目到数组,然后重新加载数据,但它不工作。

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

Thanks to lot

你做得对,

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

是正确的方法。

请仔细检查变量tableView,我看不到它的声明

make sure you have,

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

并正确连接tableView到。nib

你做对了。确保你正确设置了委托和数据源并且outlet连接到了按钮上。

编辑:也相当确定你不能只是@"废话"字符串到一个可变数组。首先尝试将文本初始化为NSString,然后将其作为指针传入。

最新更新