如何在iOS中单击UIButton时将项目插入UITableView [英] How to insert items to a UITableView when a UIButton is clicked in iOS

查看:130
本文介绍了如何在iOS中单击UIButton时将项目插入UITableView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在练习tableViews,但是当单击按钮时我无法弄清楚如何插入新项目。

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

这就是我所拥有的:

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.

有人可以告诉我如何在单击按钮时向tableView添加新项目吗?

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

非常感谢

推荐答案

你做对了,

- (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 ,我看不到它的声明。

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

确保你有, p>

make sure you have,

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

并将tableView正确连接到.nib

and properly connected the tableView to .nib

这篇关于如何在iOS中单击UIButton时将项目插入UITableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆