iOS 表格

转自http://blog.sina.com.cn/s/blog_aa6603d2010191yt.html


目标:

这次的学习是在Navigation-based Application模板中,用RootViewController class设置操作方法,使用UITableView的属性值。在导航控制器控件为程序的窗口添加上导航条,可构建多个视图连接导航按钮。这次的练习中,我在Navigation controller控件加入两个导航按钮,屏幕左上角Add按钮为表格添加新的一行,右上角Edit按钮为表格删除一行或者移动每行的顺序。当user点击edit按钮后,便会进入到编辑的视图,当user想要回到原先的视图便点击Done完成编辑。



编码:

ViewController.m文件

#import <UIKit/UIKit.h>

#import <Foundation/Foundation.h>


@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>


{

    IBOutlet UITableView *rootTableView;

    IBOutlet UIButton *editButton;

    

    NSMutableArray *dataArray;

    

    UITextField *rowField;

}


@property (nonatomic,retain) NSMutableArray *dataArray;

@property (nonatomic, retain) UITextField *rowField;

@property (nonatomic, retain) IBOutlet UITableView *rootTableView;

@property (nonatomic, retain) IBOutlet UIButton *editButton;



@end


ViewController.h文件

#import "ViewController.h"

@interface ViewController ()


@end


@implementation ViewController

@synthesize rootTableView;

@synthesize dataArray;

@synthesize editButton;

@synthesize rowField;



- (void)viewDidLoad

{

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    

    //定义内容文字

    dataArray = [[NSMutableArray alloc] initWithObjects:@"Row1", @"Row2",@"Row3",@"Row4",@"Row5", nil];

    

    //建立add按钮

    UIBarButtonItem *addButton = [[UIBarButtonItem alloc]

                                   

                                   initWithTitle:@"Add"

                                   style:UIBarButtonItemStyleBordered

                                   target:self

                                   action:@selector(AddButtonAction:)];

    

    self.navigationItem.leftBarButtonItem = addButton;

    

}


//构建操作方法,点击按钮执行

-(IBAction) EditButtonAction:(id)sender

{

    

//    [rootTableView setEditing: YES

//                     animated: YES];

    if ([sender tag] == 1) {

        [editButton setTitle:@"Done" forState:UIControlStateNormal];

        [editButton setTag:2];

        [rootTableView setEditing:YES animated:YES];

    }else if ([sender tag] == 2){

        [editButton setTitle:@"Edit" forState:UIControlStateNormal];

        [editButton setTag:1];

        [rootTableView setEditing:NO animated:YES];

    }

    

}


//添加addbutton

-(IBAction)AddButtonAction:(id)sender

{

    UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"添加一行"

                                                    message:@"" 

                                                    delegate:self 

                                           cancelButtonTitle:@"取消"

                                           otherButtonTitles:@"确定"nil];

    

    

    rowField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 38.0, 245.0, 20.0)];

    

    [rowField setBackgroundColor:[UIColor whiteColor]];

     

    [dialog addSubview:rowField];

    

    [dialog show];

    

    [dialog release];

    

    [rowField release];

    

}


-(void) alertView: (UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{

    if ((buttonIndex != [alertView cancelButtonIndex]) && (rowField.text != nil)) {

        [dataArray insertObject:[rowField text] atIndex:dataArray.count];

        

        [self.rootTableView reloadData];

        

    }

}


//表格中分组

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return 2;

}



//表格中行数

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{    

    //表格中行数等于数组内容的个数

    if (section ==0) {

        return dataArray.count;

    }

    

    if (section ==1)

    {

        return 0;

    }

    

    else {

        return 0;

    }

}


//分组标题内容设置

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

{

    //创建字符变量title

    NSString *title = nil;

    

    switch (section) {

        case 0:

            title = @"表格一";

            

            break;

            

        case 1:

            title = @"表格二";

            

            break;

            

            

        default:

            break;

    }

    

    return title;

}


//显示表格每一行内容

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    

    //创建一个字符变量,用于取得文本数据类型

    static NSString *CellIndentifier = @"cell";

    

    //建立表格行数单元格

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];

    

    //cell为空时

    

    if (cell == nil

    {

        //cell重新获取表格内容标识符

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIndentifier] autorelease];

    }

    

    //分组section0

    if (indexPath.section ==0

    {

        cell.textLabel.text =

        [dataArray objectAtIndex:indexPath.row];

    }

    

    return cell;

}





//编辑

-(BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

{

    return YES;

}




//调整

-(void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

{

    if (editingStyle == UITableViewCellEditingStyleDelete

    {

        //删除

        [dataArray removeObjectAtIndex:indexPath.row];

        

        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]

                         withRowAnimation:UITableViewRowAnimationFade];

    }

}



//上下行移动


-(void) tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath

{

    [dataArray insertObject:[dataArray objectAtIndex:sourceIndexPath.row]

                    atIndex:destinationIndexPath.row];

    

    [dataArray removeObjectAtIndex:(NSUInteger) sourceIndexPath.row+1];

}



//让表格内容位置调整的方法

-(BOOL) tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath

{

    return YES;

}


- (void)viewDidUnload

{

    [super viewDidUnload];

    // Release any retained subviews of the main view.

}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

{

    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);

}



-(void) dealloc

{

    [rootTableView release];

    rootTableView = nil;

    [rowField release];

    [dataArray release];

    dataArray = nil;

    [editButton release];

    editButton = nil;

    [super dealloc];

}

@end


保存文件,打开ViewController.xib文件, 在view中添加一个Table view控件,
将delegate和dataSource连接到File's Owner图标。
接着添加两个Button控件,将add和edit连接到File's owner图标上,保存文件运行:

运行程序:
程序运行
当点击Edit编辑,进入编辑视图。




用户可以删除数据或者调整顺序。




点击Add进行添加一行。




转自:http://www.2cto.com/kf/201312/266716.html

ios表格的操作

一:1、首先在RootViewController类中需要遵从三个协议:;然后定义两个对象:@property (retain,nonatomic)UITableView *mTableView;
@property (retain,nonatomic)NSArray *Arr;
2、其中对数组初始化,为方便利用系统封装好的一个:self.Arr=[UIFont familyNames];
对mTableView初始化:self.mTableView=[[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
//设置页眉高度
self.mTableView.sectionHeaderHeight=40;
//设置委托对象
self.mTableView.dataSource=self;
self.mTableView.delegate=self;
3、UITableViewDataSource协议中两个必须实现的方法:
//每个分段中动行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

return [self.Arr count];
}

//每行动绘制
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

static NSString *identifer=@"identifer";
UITableViewCell *pCell=[tableView dequeueReusableCellWithIdentifier:identifer];

if (nil==pCell) {

pCell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifer];
}
//获取当前行
NSUInteger cellRow=[indexPath row];
//根据行数找到数组中对应下标动数据
NSString *pTempStr=[self.Arr objectAtIndex:cellRow];
//设置文本内容
pCell.textLabel.text=pTempStr;
//设置文本字体
pCell.textLabel.font=[UIFont fontWithName:pTempStr size:18];

pCell.detailTextLabel.text=@"detailText";
pCell.imageView.image=[UIImage imageNamed:@"Default-568h@2x"];
pCell.accessoryType=UITableViewCellAccessoryCheckmark;
return pCell;



4、UITableViewDelegate协议中几个对表格某些属性加以描述的方法:
//选中某行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

NSUInteger row=[indexPath row];
NSString *pStr=[NSString stringWithFormat:@"你选中了第%d行",row];
//模态视图
UIActionSheet *pActionSheet=[[UIActionSheet alloc]initWithTitle:@"ActionSheet"delegate:self cancelButtonTitle:@"确认" destructiveButtonTitle:pStr otherButtonTitles:nil, nil];
[pActionSheet showInView:self.view];
//选中行逐渐淡出
[self.mTableView deselectRowAtIndexPath:indexPath animated:YES];
}
//调整行高方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

return 88;
}
//调整页眉高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

return 40;

}


二、对表格内容的编辑以及在表格视图中实现搜索功能:

1、对表格内容进行编辑:除了之前所学过的创建表格视图的内容,还增加了以下内容及代码:
在昨天创建表格视图的基础上,需要新建一个类MyCell,将类MyCell导入到类ViewController的.m文件里
在类MyCell中建两个Label对象和一个Button(可以由自己决定建多少对象),他们的初始化以及加载到视图过程就省略不提了,重点是将MyCell类导入到类ViewController中所做的与昨天的改变之处:
其他基本不变,主要改变的是如下:
//绘制行
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifer=@"identifer";
MYCell *pCell=(MYCell *)[tableView dequeueReusableCellWithIdentifier:identifer];
if (nil==pCell) {
pCell=[[MYCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifer];
}
pCell.NameLable.text=@"name";
pCell.ColorLable.text=@"color";
return pCell; 
}
注意其中有一个转换,注意不要忘。

2、在表格中实现搜索功能:
注意此时ViewController遵从的是两个协议;定义四个对象:
UITableView *mTableView;UISearchBar *mSeachBar;
NSMutableArray *Arr1; NSMutableArray *Arr2;
其中表视图初始化步骤省略,以下所增加代码:
//searchbar初始化
self.mSeachBar=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.mTableView.frame.size.width, 30)];
self.mSeachBar.delegate=self;
//设置当前表格的头视图
self.mTableView.tableHeaderView=self.mSeachBar;

[self.view addSubview:self.mTableView];
//初始化两个可变数组
self.Arr1=[[NSMutableArray alloc]initWithCapacity:60];
self.Arr2=[[NSMutableArray alloc]initWithCapacity:60];
for (int i=0; i<60; i++) {
NSString *pTempStr=[NSString stringWithFormat:@"%d",i];
[self.Arr1 addObject:pTempStr];
[self.Arr2 addObject:pTempStr];
}
行数返回值变为:return [self.Arr2 count];
绘制每行中其中一些代码:
//给每行加载标题(通过数组2的内容进行添加)
NSInteger row=[indexPath row];
pCell.textLabel.text=[self.Arr2 objectAtIndex:row];


//实现搜索功能的方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{

[self.Arr2 removeAllObjects];
for (NSString *str in self.Arr1){
if ([str hasPrefix:self.mSeachBar .text]) {
[self.Arr2 addObject:str];
}
}
[self.mSeachBar resignFirstResponder];
[self.mTableView reloadData];
}


三、表格的添加和删除操作以及对表格实现分组操作

1、对表格实现添加和删除操作功能:
与之前我们所学表格内容主要不同点是:在ViewController类中定义了一个可变数组,以及在视图中加了一个导航,导航右上上方有一按钮。

//初始化导航按钮
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{

if (self=[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
self.navigationItem.title=@"首页";
UIBarButtonItem *pBtnItem=[[UIBarButtonItem alloc]initWithTitle:@"BegEdit" style:UIBarButtonItemStylePlain target:self action:@selector(tableViewEdit:)];

self.navigationItem.rightBarButtonItem=pBtnItem;

}

return self;
}

//设置导航按钮标题:
- (void)tableViewEdit:(id)sender{

[sender setTitle:[self.mTableView isEditing]?@"BegEdit":@"EditEdit"];

[self.mTableView setEditing:![self.mTableView isEditing]];
}
//表格是否可编辑:
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{

if ([indexPath row]==0) {

return NO;
}
return YES;
}
//每行编辑方式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{

if ([indexPath row] % 2) {
return UITableViewCellEditingStyleDelete;
}
return UITableViewCellEditingStyleInsert;
}

//删除和增加方法
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{

if (editingStyle==UITableViewCellEditingStyleDelete) {
//在数组中移出对象
[self.mArr removeObjectAtIndex:[indexPath row]];
[self.mTableView beginUpdates];
[self.mTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight ];
[self.mTableView endUpdates];
}else if(editingStyle==UITableViewCellEditingStyleInsert){
[self.mArr insertObject:@"newCell" atIndex:[indexPath row]];
[self.mTableView beginUpdates];
[self.mTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationBottom ];
[self.mTableView endUpdates];
}
}


//是否可以移动
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{

if ([indexPath row]==2) {
return NO;
}
return YES;
}
//移动方法:
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
//获取移动前的行
NSUInteger fromRow=[sourceIndexPath row];
//将要移动到的行
NSUInteger toRow=[destinationIndexPath row];
//获取数组中移动前下标对应的对象
id obj=[self.mArr objectAtIndex:fromRow];
//从数组中删除
[self.mArr removeObjectAtIndex:fromRow];
//在新的位置加入
[self.mArr insertObject:obj atIndex:toRow];
}


注意表格行数返回的是:return [self.mArr count];
每行表格标题设为:NSUInteger row=[indexPath row];
pCell.textLabel.text=[self.mArr objectAtIndex:row];


2、对表格实现分组:
首先建一个表格视图,注意所建的表格视图风格是:UITableViewStyleGrouped;
然后创建一个plist文件,创建方法省略(在resource里面选中property list,然后创建),在plist文件写入自己想在分组表格中显示的内容。

获取plist文件路径,并将它赋值给字典,然后将字典中的内容分配给数组,实现代码如下:
NSString *path=[[NSBundle mainBundle]pathForResource:@"Data" ofType:@"plist"];
self.mDic=[NSDictionary dictionaryWithContentsOfFile:path];
self.mArr=[[self.mDic allKeys]sortedArrayUsingSelector:@selector(compare:)];
此时创建的表格视图每组中行数返回值为:return [[self.mDic objectForKey:[self.mArr objectAtIndex:section]]count];
绘制每行时每行的标题:pCell.textLabel.text=[[self.mDic objectForKey:[self.mArr objectAtIndex:section]]objectAtIndex:row];

//每组的标签:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

return [self.mArr objectAtIndex:section];
}

//右侧索引栏的添加方法:
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{

return self.mArr;
}

而组数返回值为:return [self.mArr count];


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值