UITableView

要进行tableView的相关设置需要遵守以下两个协议

@interface RootViewController()<UITableViewDelegate, UITableViewDataSource>
@end

初始化

//此处y轴设为64是44的NavigationBar+20的手机导航栏的高度
UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,64,414,736-64)];
tableView.delegate = self;
tableView.dataSource = self;
[self.view addSubview:tableView];

一般的tableView创建时写这些内容就差不多完成了

实现协议方法

#pragma mark 必须实现的方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    //此方法返回的是tableView的分区数
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowInSection:(NSInteger)section{
    //此方法返回的是tableView不同分区的行数
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView CellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //此方法返回的是tableView的cell,tableView的cell使用的是重用机制,即创建有限个cell来应对无限个条目,
    //当一个cell即将在视图中出现时,从重用池中调用一个cell来使用,如果没有则创建,对应的当一个cell已经从视
    //图中消失时,将其放入重用池
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    //identifier必须上下一致,这是在重用池中取用cell的标识
    if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    
    }
    return cell;
}

此处创建的是系统提供的cell,我们实际工作中一般都会使用自定义cell。
创建cell除了以上方法之外还可以使用注册模式

[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
//提前注册cell的类型,自定义cell或者系统cell都可以这样注册

在返回cell的方法中

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

在前面注册之后,后面取用的方法中需附带设置indexPath

#pragma mark 其他方法
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
//设置分区标题
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
//设置行高
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;
//设置分区标题视图,和分区标题的方法二选一即可
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
//设置分区标题的高度
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
//cell的点击事件实现方法
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、简介 <<UITableView(或简单地说,表视图)的一个实例是用于显示和编辑分层列出的信息的一种手段 <<...
    无邪8阅读 10,736评论 3 3
  • 概述在iOS开发中UITableView可以说是使用最广泛的控件,我们平时使用的软件中到处都可以看到它的影子,类似...
    liudhkk阅读 9,098评论 3 38
  • UITableViewCell控件空间构造 cell的子控件是contentView,contentView的子控...
    CoderZXS阅读 741评论 0 1
  • 版权声明:未经本人允许,禁止转载. 1. TableView初始化 1.UITableView有两种风格:UITa...
    萧雪痕阅读 2,920评论 2 10
  • 序引 本系列文章将介绍iOS开发中的UITableView控件,将会分成四篇文章完整的讲述UITableView的...
    yetCode阅读 2,304评论 3 40