UITableView

UITableView的样式

UITableView是iOS开发中非常重要的控件之一,它能够展示多行数据,支持滚动.在大部分APP中都占有很大的比重.

  • UITableView的创建方式:
    • storyboard:直接拖到控制器中即可.
    • 代码
    //代码创建
    UITableView *tableView = [[UITableView alloc] init];
    //设置frame
    tableView.frame = self.view.bounds;
    [self.view addSubview:tableView];
  • UITableView有两种样式:plain和grouped.如图所示,
    图1是plain样式即所有的cell都在黏在一起,没有明显的区分.图2是grouped样式,是分组的.
图1
图2

可以看到两种格式的区别非常明显.

在UITableView中,每一个单元格被称为cell,如果想在UITableView中显示数据,需要设置UITableView中cell的数量及每个cell显示的内容.UITableView并不能直接显示数据,它需要设置数据源(datasource),数据源遵守<UITableViewDataSource>协议,并实现其中对应的方法设置数据及内容即可.

<UITableViewDataSource>中常用的方法:

@required(必须实现的)
    //返回第section行的row数量
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
    //返回第indexPath.row行的cell内容
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
以上这两个方法会调用一次或多次,次数根据设置的section数量及每个section的cell数量而定.在开发中一般通过模型来传递数据,在控制器中创建一个数组接收模型数据,然后加载到cell中显示.

@optional(可选的)
     //返回section的数量,默认为1
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; 
    //返回grouped样式中每组的头部标题
    - (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section; 
    //返回grouped样式中每组的尾部标题
    - (nullable NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section;

UITableViewCell的创建及重用

UITableViewCell在创建时,系统会自动设置为懒加载状态.但为了高效利用每一个cell,我们需要设置cell的重用标识(identfier),加载cell时先从缓存池中查找可用的cell.

UITableViewCell的创建方式1:纯代码

  • 设置如下:
  //设置indexPath.row行的cell内容
  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
     //设置重用标识
     static NSString *ID=@"cell";
     //根据重用标识从缓存池中查找可用cell
     UITableViewCell *cell=[self.tableView dequeueReusableCellWithIdentifier:ID];
     //找不到可用cell,手动创建标识为ID的cell
      if (cell == nil) {
         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
     //板式输出
     cell.textLabel.text = [NSString stringWithFormat:@"test--%zd",indexPath.row];
     //返回cell
     return cell; 
}

UITableViewCell的创建方式2:storyboard

  • 设置如下:
storyboard设置重用标识

在代码中实现以下方法:

  //设置indexPath.row行的cell内容
  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
     //设置重用标识
     static NSString *ID=@"cell";
     //根据重用标识从缓存池中查找可用cell,如果找不到,系统会根据storyboard中的cell标识创建cell.
     UITableViewCell *cell=[self.tableView dequeueReusableCellWithIdentifier:ID];
     //板式输出
     cell.textLabel.text = [NSString stringWithFormat:@"test--%zd",indexPath.row];
     //返回cell
     return cell; 
}

UITableViewCell的创建方式3:register

实现方法如下:

    //先在控制器中对cell的标识注册
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
     //设置重用标识
     static NSString *ID=@"cell";
     //根据重用标识从缓存池中查找可用cell,如果找不到,系统会根据注册的cell标识创建cell.
     UITableViewCell *cell=[self.tableView dequeueReusableCellWithIdentifier:ID];
     //板式输出
     cell.textLabel.text = [NSString stringWithFormat:@"test--%zd",indexPath.row];
     //返回cell
     return cell; 
}

UITableView及UITableViewCell的一些属性

UITableView继承自UIScrollView,如果成为了UITableView的代理,也就意味着同样遵守了UIScrollView的代理协议,可以实现UIScrollViewDelegate中的方法来监听UITableView的滚动事件.

在UITableView中每个section的头部或底部,如果想设置图片,可以实现以下方法.

  //在section的底部区域显示一个UIView控件
  - (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return expression;
}
  //在section的头部区域显示一个UIView控件
  - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return expression;
}

如果想监听点击某一行,可以实现以下方法:

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

如果想设置tableView不显示分割线,可以设置以下属性

   self.tableView separatorStyle = UITableViewCellSeparatorStyleNone;

UITableViewCell中的控件其实都添加到了cell中的Content View上面,在自定义控件添加时,需要调用
[cell.contentView addSubview:(nonnull UIView *)]方法,添加到cell的.contentView中去,这也是苹果官方推荐添加的一种方式.

创建自定义等高cell方式1:storyboard

  1. 在storyboard中放入一个UITableViewController(或者UIViewController中嵌套一个UITableView),系统会默认自带一个cell.

2.更改cell的重用标识(identfier)

3.给每个cell绑定一个tag,方便设置数据.

4.在数据源方法中设置cell的显示内容

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID=@"cell";
        
    UITableViewCell *cell=[self.tableView dequeueReusableCellWithIdentifier:ID];
    
    //获取模型数据
    DLShop *shop = self.shops[indexPath.row];
    //给cell赋值
    UIImageView *iconView = (UIImageView *)[cell viewWithTag:1];
    iconView.image = [UIImage imageNamed:shop.icon];
    
    UILabel *titleLabel = (UILabel *)[cell viewWithTag:2];
    titleLabel.text = shop.title;
    
    UILabel *priceLabel = (UILabel *)[cell viewWithTag:3];
    priceLabel.text = shop.price;
    
    UILabel *buyCount = (UILabel *)[cell viewWithTag:4];
    buyCount.text = shop.buyCount;
    
    return cell;
}
storyboard中自定义cell需要用到tag,开发中会比较不方便,不推荐这种自定义方法.

创建自定义等高cell方式2:自定义cell

1.新建一个类

2.在storyboard中选中cell,修改class为类名

3.将cell中的控件拖线至新建类中

4.在新建类.h文件中包含模型类,定义一个模型属性接收模型数据

#import <UIKit/UIKit.h>
@class DLShop;

@interface DLShopCell : UITableViewCell
// 定义模型属性,接收数据
@property(nonatomic,strong) DLShop *shop;
@end

5.在新建类.m文件中,导入模型头文件,重写模型属性的set方法,设置传入的模型数据到子控件>

@implementation DLShopCell

-(void)setShop:(DLShop *)shop{
    
    _shop = shop;
    
    self.icon.image = [UIImage imageNamed:shop.icon];
    self.title.text = shop.title;
    self.price.text = [NSString stringWithFormat:@"¥%@",shop.price];
    self.buyCount.text = [NSString stringWithFormat:@"%@人已购买",shop.buyCount];
    
}
@end

6.在控制器中实现数据源方法,设置数据

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID=@"cell";
    
    // 新建一个DLShopCell类型的cell,保证创建的cell是我们自定义的
    DLShopCell *cell=[self.tableView dequeueReusableCellWithIdentifier:ID];
    
    //获取模型数据
    cell.shop = self.shops[indexPath.row];
    
    return cell;
}

自定义类名创建cell比较方便,能很好的封装cell控件,设置数据也很方便.

创建自定义等高cell方式3:xib自定义cell

1.新建一个xib文件,名称与自定义类名保持一致.

2.修改xib的class为自定义类的名称,保证创建时能够找到xib文件

3.设置xib内部cell的重用标识

4.从xib拖线至自定义类中

5.在自定义类.h文件中包含模型类,定义一个模型属性接收模型数据,同时提供一个类方法,将tableView传进去.

#import <UIKit/UIKit.h>
@class DLShop;

@interface DLShopCell : UITableViewCell
// 定义模型属性,接收数据
@property(nonatomic,strong) DLShop *shop;

// 外界传入tableView,返回DLShopCell类型的cell
+ (instancetype)cellWithTableView:(UITableView *)tableView;
@end

6.在.m文件中实现以上方法.

@implementation DLShopCell
//重写模型属性set方法设置传入模型数据到子控件
-(void)setShop:(DLShop *)shop{
    _shop = shop;
 
    self.icon.image = [UIImage imageNamed:shop.icon];
    self.title.text = shop.title;
    self.price.text = [NSString stringWithFormat:@"¥%@",shop.price];
    self.buyCount.text = [NSString stringWithFormat:@"%@人已购买",shop.buyCount]; 
}
//实现cellWithTableView:将外界传入tableView查找缓存池数据,如果没有,创建并返回DLShopCell类型的cell
+ (instancetype)cellWithTableView:(UITableView *)tableView{
    static NSString *ID = @"cell";
    DLShopCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([DLShopCell class])  owner:nil options:nil] lastObject];
    }
    return cell;
}
@end
xib自定义cell完美实现了控件的封装,将控件的所有属性都包装在自己内部,推荐使用xib自定义cell,方便后期维护及使用.

懒加载

在控制器中新建数组属性保存模型数据时,一般会采用懒加载思想.步骤如下:

1.在控制器文件中定义一个数组,保存传入的模型数据.

@interface TestTableViewController ()
// 用来保存传入的模型数据
@property(nonatomic,strong) NSArray *shops;
@end

2.重写属性的get方法,用到时再调用该属性,以实现懒加载.

- (NSArray *)shops{
    
    if (_shops == nil) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"shops.plist" ofType:nil];
        //取出字典数据转为数组
        NSArray *dictArr = [NSArray arrayWithContentsOfFile:path];
        //创建一个空的可变数组接收模型数据
        NSMutableArray *dealArrM = [NSMutableArray array];
        //遍历数组取出字典数据
        for (NSDictionary *dict in dictArr) {
            //定义模型接收字典数据
            DLShop *shop = [DLShop shopWithDict:dict];
            //将数据添加到模型
            [dealArrM addObject:shop];
        }//传递模型到成员变量中
        _shops = dealArrM;
    }
    return _shops;
}

设置tableview有值时才显示分割线

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

推荐阅读更多精彩内容