UITableView

自定义单元格

表格无论有多少中自定义单元格样式 每一种自定义单元格都有复用的能力
所以每一个单元格都要带有一个静态局部变量作为唯一标识

自定义单元格纯手写的

需要在自定义单元格类中重写-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier方法,并且把所有要创建的控件定义在其中

方式一:直接在cellForRowAtIndexPath中实现并判断

  • (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * string = @"custom";
    FirstTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (cell == nil) {
    cell = [[FirstTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:string];
    }
    cell.nameLabel.text = dataSource[indexPath.row][@"personName"];
    cell.phoneLabel.text = dataSource[indexPath.row][@"phoneNum"];
    return cell;
    }

方式二:在创建表格/集合视图的时候调用registerClass: forCellWithReuseIdentifier:

方法,且在cellForRowAtIndexPath方法中不用判断为空,可直接重用/赋值

自定义单元格带有XIB文件的

//为表格添加单元格的方法有两种:
//<1>先注册单元格文件
[table registerNib:[UINib nibWithNibName:@"CustomTableViewCell" bundle:nil] forCellReuseIdentifier:@"string"];
此方法在你创建UITableView的时候使用
可以不设置xib上的indentifier属性值
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//单元格的标识上下必须完全相同
CustomTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"string"];
//此处不需要判断单元格是否为空因为上面的viewDidLoad方法中已经注册过单元格了 所以一定不会为空
cell.nameLabel.text = dataSource[indexPath.row][@"personName"];
cell.phoneLabel.text = dataSource[indexPath.row][@"phoneNum"];
return cell;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//<2>使用XIB定义单元格的第二种方法
static NSString * string = @"string";
//[注意]此处的静态局部变量的内容一定要和XIB文件中单元格的identifier属性的内容完全相同 使得cell能够重用 否则单元格会不断的创建 最终导致内存溢出/程序崩溃
CustomTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:string];
if(cell == nil)
{
cell = [[[NSBundle mainBundle] loadNibNamed:@"CustomTableViewCell" owner:self options:nil] lastObject];
}
cell.picImageView.image = [UIImage imageNamed:dataSource[indexPath.row][@"imageName"]];
cell.titleLabel.text = dataSource[indexPath.row][@"title"];
cell.contentLabel.text = dataSource[indexPath.row][@"content"];
cell.collectionLabel.text = dataSource[indexPath.row][@"collection"];
return cell;
}

扩展

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]
如果需要使用这个方法,你必须使用配套的方法来一起用,下面两个配套方法选其一:

  • (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(5_0);
  • (void)registerClass:(Class)cellClass forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(6_0);
    上述两个方法在你创建UITableView的时候调用

tableview使用

tableview刷新,移动到最后一行

[_tableView reloadData];
NSIndexPath * indexPath = [NSIndexPath indexPathForRow:_dataSource.count-1 inSection:0];
[_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
不断改变edit的编辑状态
[_tableView setEditing:editing animated:YES];

确定cell的编辑模式

  • (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
    return UITableViewCellEditingStyleDelete;
    }else
    return UITableViewCellEditingStyleInsert;
    }

//提交编辑的结果

  • (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if(editingStyle == UITableViewCellEditingStyleDelete){
    //先删除数据源部分(先删除某一行)
    //找到对应的组 再删除指定行
    [_dataArray [indexPath.section]removeObjectAtIndex:indexPath.row];
    //重新刷新所有的代理方法(方式一)
    //[_tableView reloadData];
    //从tableview中删除对应的行(方式二)
    [_tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];//从左方消失(动画)
    }else{//插入
    NSString * str = @"sdf";
    //找到对应的组 再插入指定行
    [_dataArray [indexPath.section]insertObject:str atIndex:indexPath.row];
    [_tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationBottom];
    }
    }

//让cell可以移动

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

//更改数据源中的数据顺序
//先保存要移动的数据
NSString * number = [[_dataArray objectAtIndex:sourceIndexPath.section]objectAtIndex:sourceIndexPath.row];
[[_dataArray objectAtIndex:sourceIndexPath.section]removeObjectAtIndex:sourceIndexPath.row];
[[_dataArray objectAtIndex:destinationIndexPath.section]insertObject:number atIndex:destinationIndexPath.row];
}
//缩进
-(NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath{
return indexPath.row;
}

//添加多个按钮

  • (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewRowAction * deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
    //实现方法
    //从总数据源里删掉对应的数据
    [_dataArray [indexPath.section]removeObjectAtIndex:indexPath.row];
    //从表格里删除对应的行
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    }];

UITableViewRowAction * singAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"标记" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
cell.backgroundColor = [UIColor redColor];
}];
UITableViewRowAction * topAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"置顶" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
NSString * str = [[_dataArray objectAtIndex:indexPath.section]objectAtIndex:indexPath.row];
[[_dataArray objectAtIndex:indexPath.section]removeObjectAtIndex:indexPath.row];
[[_dataArray objectAtIndex:indexPath.section]insertObject:str atIndex:0];
//刷新
[tableView reloadData];
}];
return @[deleteAction,singAction,topAction];
}

为表格添加搜索索引

  • (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    NSMutableArray * array = [[NSMutableArray alloc]init];
    for (int i = 'A'; i < 'Z'; i++) {
    [array addObject:[NSString stringWithFormat:@"%c",i]];
    }
    return array;
    }

动态设置单元格高度

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * string = @"string";
CustomTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:string];
if(cell == nil)
{
cell = [[CustomTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
}

计算动态desc的高度

CGRect rect = [subDataSource[indexPath.row] boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
cell.detailLabel.frame = CGRectMake(0, 80, [UIScreen mainScreen].bounds.size.width, rect.size.height);
NSLog(@"%f",cell.detailLabel.frame.size.height);
lable的坐标原点的坐标以及宽度一定要和自定义单元格上label的初始值完全相同 只有高度是动态的
CGRect rect = [subDataSource[indexPath.row] boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
cell.detailLabel.frame = CGRectMake(0, 80, [UIScreen mainScreen].bounds.size.width, rect.size.height);
return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//动态计算cell高度,固定高度+动态label的高度
NSString *desc = subDataSource[indexPath.row];
//计算动态desc的高度
CGRect rect = [desc boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
//100是固定高度 rect.size.height是计算得到的动态高度
return 80 + rect.size.height;
}

使用xib高度自适应时

//允许单元格自适应
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 44.0;

一个section刷新

NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:2];
[tableview reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];

一个cell刷新

NSIndexPath *indexPath=[NSIndexPath indexPathForRow:3 inSection:0];
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];

//允许单元格自适应
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 44.0;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容

  • 概述在iOS开发中UITableView可以说是使用最广泛的控件,我们平时使用的软件中到处都可以看到它的影子,类似...
    liudhkk阅读 8,834评论 3 38
  • 1.创建一个UITableView对象 ITableView *tableView = [[UITableView...
    桐生一猫阅读 1,332评论 0 5
  • UITableView 表格视图一 UITableView1.1是什么?以列表的方式展示数据的一种控件,且继承自...
    037e3257fa3b阅读 219评论 0 1
  • 插入行。删除行。折叠区。设置索引。刷新表格。注册cell。 //UITableView的ADD // NSStri...
    nothing_c阅读 194评论 0 0
  • 版权声明:未经本人允许,禁止转载. 1. TableView初始化 1.UITableView有两种风格:UITa...
    萧雪痕阅读 2,814评论 2 10