UITableView

13 篇文章 0 订阅
8 篇文章 0 订阅

关于UITableView的一点详解

(1)创建UITableView的方法有下面几种,使用storyboard,xib或者pure code,前面两种我不太熟悉,我一般用的是纯代码构建UITableView

(2)UITabelView最重要的两种协议dataSource和delegate

1.dataSource
这个是UITableView的数据源,涉及到列表的数据改动的协议都在这里面,比如:删除行,添加行,设置UITableViewCell的数据等等

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;    //设置行数
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;    //设置cell里面的内容

2.delegate
这个是UITableView的一些行为规定,比如:点击行为,设置行高等等

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;

(3)下面详述一下UITableView的具体实现

1.新建一个UITableView,并设置UITableView的dataSource和delegate,然后把她加到具体的view上面

        UITableView *table = [[UITableView alloc] initWithFrame: [UIScreen mainScreen].bounds style: UITableViewStylePlain];
        table.delegate = self;
        table.dataSource = self;
        [self.view addSubview: table];

2.设置delegate和dataSource的对象需要实现相应的协议
CollectionViewController.h文件实现

@interface  CollectionViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>

@end

CollectionViewController.m文件实现

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.items.count;    //返回行数
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CollectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[CollectionTableViewCell reuseIdentifier] forIndexPath: indexPath];    //自定义一个cell,需要注册一个class,重用标识符可以是改class的类名字符串
    [cell setUpData: self.items[indexPath.row]];    //把数据传入cell中
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 110;    //返回行高
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //do something    //选择某一行
}

基本上一个UITableView就简单实现了,当然,UITableView的很多方法没有讲到,感兴趣的同学可以自行去尝试。

Tips:

1.如果数据是网络获取的,无论是你在这之前设置了UITableView的delegate和dataSource还是在获取到数据之后设置,最好重新reload一下,否则可能出现刚开始没有数据显示在屏幕上,然后滑动一下数据又出来的现实,这是因为在数据来之前,改UITableView已经加载了,这时候还没有数据,所以需要reload
2.如果你是把view和controller分开写,view初始化的时候没有设置frame,那么也会有1中的问题
3.如果controller太臃肿,可以把UITableView的delegate和dataSource分离出去,专门放到一个文件中
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值