IOS系列——UItableview的基础使用

来源:互联网 发布:股票基本面软件 编辑:程序博客网 时间:2024/05/16 12:33

在IOS中,众所周知,UiTableview使用的时候很多,而且知识点也很多,作为一个菜鸟来讲,首先要先知道基础的使用方法

Uitableview的使用,要实现它的协议和数据源,就是在.h文件中实现

@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>

下面开始简单介绍一下在页面中添加一个tableview;


  1,在.h文件中完成以下代码

#import <UIKit/UIKit.h>@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>@property (nonatomic,retain) NSMutableArray *listdata;@property (nonatomic,retain) UITableView *tableview;@end
然后在.m文件中看看添加什么代码

2、在viewDidLoad中实现listdata(cell中的数据)和 tableview的初始化

tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStyleGrouped];    listdata = [[NSMutableArray alloc]initWithObjects:@"北京",@"上海",@"深圳",@"武汉",@"枣阳", nil];//    listdata = [[NSMutableArray arrayWithObjects:@"北京",@"上海",@"深圳",@"武汉",@"枣阳", nil]retain];    tableview.delegate = self;    tableview.dataSource = self;    [self.view addSubview:tableview];        [tableview release];
细心的人可以看到,在这listdata用实例方法来初始化的,但是我并没有release,那是因为在后面的函数还要使用,当然,如果一定要遵守“谁创建,谁释放”的原则的话,在这里英爱先retain一次,然后在release,在这里,我还有注释的一行,这个使用静态方法来初始化listdata,在后面加了一个retain。不过一般是不用这种方法,因为静态方法自动释放的时候是使用autorelease,然后使用retain的话,不太好,不过如果你一定要用这个方法,似乎也没什么问题

3、设置tableview有多少行

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    return [listdata count];    [listdata release];}

4、设置tableview中cell(单元)的内容

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];    if (cell == nil) {        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];    }    int row = [indexPath row];    cell.textLabel.text = [listdata objectAtIndex:row];    cell.imageView.image = [UIImage imageNamed:@"small.png"];    cell.accessoryType = UITableViewCellSelectionStyleGray;    cell.detailTextLabel.text = @"详细信息";    return  cell;    [cell release];    }


这里面有一个需要用图来解释的是 cell的type   
typedef NS_ENUM(NSInteger, UITableViewCellStyle) {    UITableViewCellStyleDefault,// Simple cell with text label and optional image view (behavior of UITableViewCell in iPhoneOS 2.x)    UITableViewCellStyleValue1,// Left aligned label on left and right aligned label on right with blue text (Used in Settings)    UITableViewCellStyleValue2,// Right aligned label on left with blue text and left aligned label on right (Used in Phone/Contacts)    UITableViewCellStyleSubtitle// Left aligned label on top and left aligned label on bottom with gray text (Used in iPod).};             // available in iPhone OS 3.0

系统自带的是这四种,根据上面的代码,以此显示的效果图为:

上面的一些代码可以实现将一个tableview添加到页面


5、cell的点击事件

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{    switch (indexPath.row) {        case 0:{            secondview *second = [[secondview alloc]initWithNibName:@"secondview" bundle:nil];            [self presentViewController:second animated:NO completion:^{}];            [second release];        }            break;        case 1:{            thirdview *third = [[thirdview alloc]initWithNibName:@"thirdview" bundle:nil];            [self presentViewController:third animated:NO completion:^{}];            [third release];        }            break;                    default:            break;    }//    NSString *msg = [[NSString alloc] initWithFormat:@"你选择的是:%@",[listdata objectAtIndex:[indexPath row]]];//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];//   //    [alert show];//    [msg release];}

其他的一些函数:

 1)、设置缩进

//设置缩进- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath{    return [indexPath row];}

 2)、弹出一个删除按钮

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{    NSLog(@"执行删除操作");}

自定义弹出按钮的文字

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{    return @"删除";}

3)、设置行高

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    return 70;}

4)、设置cell的背景色
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{    if ([indexPath row] % 2 == 0) {        cell.backgroundColor = [UIColor blueColor];    } else {        cell.backgroundColor = [UIColor greenColor];    }} 


UITableViewCell的选中时的颜色

1)给定的集中默认

//无色  cell.selectionStyle = UITableViewCellSelectionStyleNone;  //蓝色  cell.selectionStyle = UITableViewCellSelectionStyleBlue;  //灰色  cell.selectionStyle = UITableViewCellSelectionStyleGray;  

2) 自定义颜色
cell.selectedBackgroundView = [[[UIView alloc] initWithFrame:cell.frame] autorelease];  cell.selectedBackgroundView.backgroundColor = [UIColor xxxxxx];  

3)自定义选中的背景图

cell.selectedBackgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cellart.png"]] autorelease];   //还有字体颜色   cell.textLabel.highlightedTextColor = [UIColor xxxcolor];  [cell.textLabel setTextColor:color];//


4)cell没有选中效果 

[cell setSelectionStyle:UITableViewCellSelectionStyleNone];

分隔线

设置分隔线的颜色

[theTableView setSeparatorColor:[UIColor xxxx ]];

设置分割线的样式

_tableview.separatorStyle = UITableViewCellSeparatorStyleNone;





5)、设置tableview的段落
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{    return 1;}

如果设置段落的话 

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    if (section == 0) {        return 3;    }    if (section == 1) {        return 2;    }}


补充:

当设置tableview为UITableViewStylePlain时; 默认会出现满屏的cell(即使cell只有1个)就会有很多空白的cell  如果要去掉这些的话 :可用

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{    UIView *view=[[UIView alloc] init];    [view setBackgroundColor:[UIColor clearColor]];    return view;}
或者
-(UIView*)tableView:(UITableView*)tableView viewForFooterInSection:(NSInteger)section   {        if([self numberOfSectionsInTableView:tableView]==(section+1)){                return [UIView new];        }           return nil;  } 

还有一个问题 ,每次点击cell的时候 会有背影加重的情况,默认是不会复原的 需要自己来写

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{    [tableView deselectRowAtIndexPath:indexPath animated:YES];}
或者如果点击跳转到其他页面的话 还可以这样写
-(void)viewWillAppear:(BOOL)animated{    [self.tableview deselectRowAtIndexPath:[self.tableview indexPathForSelectedRow] animated:YES];}



获取tablecell的高度 

cell.frame.size.height

cell.contentView.frame.size.height


获取某一个cell

NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];MyOwenTableViewCell *cell = (MyOwenTableViewCell *)[_myTabView cellForRowAtIndexPath:index];

刷新某一个cell     刷新 section = 0 row = 0 的cell
NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];[_myTabView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationNone];

刷新某一个section  
NSRange range = NSMakeRange(indexPath.section, 1);NSIndexSet *sectionToReload = [NSIndexSet indexSetWithIndexesInRange:range];/*NSMutableIndexSet是一个可变的集合,其使用方法如:NSMutableIndexSet *idxSet = [[NSMutableIndexSet alloc] init];        [idxSet addIndex:5];    [idxSet addIndex:2];    [idxSet addIndex:8];    [idxSet addIndex:12];   //  添加 4到13的索引值    [idxSet addIndexesInRange:NSMakeRange(4, 10)];*/[_tableview reloadSections:sectionToReload withRowAnimation:UITableViewRowAnimationBottom];

tableview的索引

首先 在不知道tablview有索引的时候,对这个东西感觉很高深,但是知道有这些东西后,几个简单的代理就可以实现  类似于通讯录的功能
首先需要的是两个数组。一个 是cell的数据  一个是索引的数据
sectionTitles       = [[NSArray alloc] initWithObjects:                           @"A",@"C",@"F",@"G",@"H",@"M",@"S",@"T",@"X",@"Z", nil];    contentsArray       = [[NSArray alloc] initWithObjects:                           @[@"阿伟",@"阿姨",@"阿三"],                           @[@"蔡芯",@"成龙",@"陈鑫",@"陈丹",@"成名"],                           @[@"芳仔",@"房祖名",@"方大同",@"芳芳",@"范伟"],                           @[@"郭靖",@"郭美美",@"过儿",@"过山车"],                           @[@"何仙姑",@"和珅",@"郝歌",@"好人"],                           @[@"妈妈",@"毛主席"],                           @[@"孙中山",@"沈冰",@"婶婶"],                           @[@"涛涛",@"淘宝",@"套娃"],                           @[@"小二",@"夏紫薇",@"许巍",@"许晴"],                           @[@"周恩来",@"周杰伦",@"张柏芝",@"张大仙"],nil];

  实现几个简单的tableview的初始化

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{    return  contentsArray.count;}-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    static NSString *str = @"cell";    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];    if (!cell) {        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];    }        cell.textLabel.text = contentsArray[indexPath.section][indexPath.row];            return cell;}-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    return ((NSArray *)contentsArray[section]).count;}

下面就是一些索引的数据

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{    return [sectionTitles objectAtIndex:section];}
实现headview的数据填充,不过用这个方法填充数据  有一点就是不知道怎么实现背景色和 文字颜色的改变,可以考虑用自定义headview的方法  可扩展性就很大
// 索引目录-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{    return sectionTitles;}-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{    // 获取所点目录对应的indexPath值    NSIndexPath *selectIndexPath = [NSIndexPath indexPathForRow:0 inSection:index];       // 让table滚动到对应的indexPath位置    [tableView scrollToRowAtIndexPath:selectIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];        return index;}

在这里也说说索引的几个基本参数

_tableview.sectionIndexBackgroundColor = MAINCOLOR;    //索引的背景颜色    _tableview.sectionIndexTrackingBackgroundColor = [UIColor blackColor];  //当索引条被点击的时候 出现的颜色    _tableview.sectionIndexMinimumDisplayRowCount = 20;<span style="white-space:pre"></span>// tablview 总共有多少行才会显示索引栏    _tableview.sectionIndexColor = [UIColor whiteColor];<span style="white-space:pre"></span>//索引上文字的颜色





tableview 删除的问题

单行删除  

这个其实很简单  不过主要是由知道几个方法

//当cell 从删除状态 变为 正常状态-(void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath{    flag = NO;    [editButton setTitle:@"编辑" forState:0];}//当cell 从正常状态 变为 删除状态-(void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath{    [editButton setTitle:@"完成" forState:0];    flag = YES;}//设置 出现的按钮的文字-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{    return @"删除";}//设置 cell是否可编辑-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{    return YES;}//设置 cell出现删除按钮的  按钮事件-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{        if (editingStyle == UITableViewCellEditingStyleDelete) {            }}


又一个按钮(比如右上角的编辑按钮) 可以直接让tableview成为编辑状态

全局bool

bool  flag;

-(void)bianji{        if (!flag)    {        [editButton setTitle:@"完成" forState:0];        [_tableview setEditing:YES animated:YES];        flag = YES;    }    else    {        [editButton setTitle:@"编辑" forState:0];        [_tableview setEditing:NO animated:YES];        flag = NO;    }}

以上这些方法 就可以实现cell的当行删除


多行删除

多行删除  爱实现上面的方法 之外  还需要一个特定的方法 在这里说2种实现多行删除的方法

推荐使用第一种
[_tableview setAllowsMultipleSelectionDuringEditing:YES];
这个方法  有好处是  比如点击编辑按钮的时候 ,cell会出现多行删除的 按钮  同时 对于单行删除没有影响,也就是说  cell左滑  出现delege 按钮还是可以的  单行删除和多行删除 i可以共存的

- (UITableViewCellEditingStyle)tableView:( UITableView *)tableView editingStyleForRowAtIndexPath:( NSIndexPath *)indexPath{    return    UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;}
这个方法弊端就是   当实现了这个方法   单行删除无效了   目前还没找到原因


原创粉丝点击