一 茬贵、 在AppDelegate.h中設(shè)置導(dǎo)航欄
- 導(dǎo)入頭文件 ViewController.h
#import "ViewController.h"
2
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// 導(dǎo)航控制器
ViewController *vc = [[ViewController alloc] init];
UINavigationController *theNav = [[UINavigationController alloc] initWithRootViewController:vc];
self.window.rootViewController = theNav;
return YES;
}
二、首先 我們要用到表格的兩個(gè)協(xié)議方法以及一個(gè)彈出框的協(xié)議方法
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>
三惠昔、 創(chuàng)建表格與數(shù)組的全局變量,方便下面的調(diào)用
UITableView *theTable;
NSMutableArray *array;
四 缤苫、在viewDidLoad中 對(duì)表格進(jìn)行初始化,并設(shè)置的代理, 為其設(shè)置兩個(gè)按鈕 ,以及將 數(shù)組進(jìn)行初始化并賦值
- (void)viewDidLoad
{
[super viewDidLoad];
// 初始化表格
theTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
// 代理
theTable.delegate = self;
theTable.dataSource = self;
[self.view addSubview:theTable];
// 右按鈕
UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStylePlain target:self action:@selector(right)];
self.navigationItem.rightBarButtonItem = right;
// 左按鈕
UIBarButtonItem *left = [[UIBarButtonItem alloc]initWithTitle:@"編輯" style:UIBarButtonItemStylePlain target:self action:@selector(left)];
self.navigationItem.leftBarButtonItem = left;
array = [[NSMutableArray alloc] initWithObjects:@"小李",@"小王",@"小紅", nil];
}
對(duì)兩個(gè)按鈕的方法 進(jìn)行設(shè)置
// 編輯
-(void)left
{
[theTable setEditing:!theTable.editing animated:YES];
}
// 添加
-(void)right
{
UIAlertView * alert =[[UIAlertView alloc]initWithTitle:@"信息" message:@"添加" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"確定", nil];
alert.alertViewStyle=UIAlertViewStylePlainTextInput;
alert.delegate=self;
[alert show];
}
彈出框的設(shè)置
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1)
{
UITextField *field = [alertView textFieldAtIndex:0];
[array addObject:field.text];
[theTable reloadData];
}
}
表格的協(xié)議方法
#pragma mark - 表格方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@""];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
}
cell.textLabel.text = array[indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
[array removeObjectAtIndex:indexPath.row];
[theTable reloadData];
}
此代碼實(shí)現(xiàn)了 表格的左滑刪除功能以及添加數(shù)據(jù)的功能