2018-06-12

UITableView与UICollecView的使用

【本文目录】

[TOC]

推荐阅读及本文内主要来源

【iOS开发系列--UITableView全面解析】

【UICollectionView及其新功能drag and drop 】

【在UIScrollView、UICollectionView和UITableView中添加UIRefreshControl实现下拉刷新】

请直接看原文比较好哈哈哈哈。

本文基本上是拙劣地把几篇内容重新以自己的流程整理了思绪,以备后面使用。。。

1.UITableView


1.1UITableView的使用

UITableview常用来实现有大量相同格式信息的视图,如我们常见的设置界面,电话通讯录界面,好友列表,微博界面就是通过UITableView来实现。示意如图:


设置界面.png

原图地址(https://images0.cnblogs.com/blog/62046/201408/232318440491185.png)

好友界面.png

原图地址(https://images0.cnblogs.com/blog/62046/201408/232318465964629.png)

UITableView是UIScrollView的子类,它允许我们进行纵向滚动,UITableViewCell对象构建了UITableView列表中的一行元素,UITableView使用这些cell对象进行绘制,UITableView中可以包含多组(section)的cell,每组可以有不同的cell数,如设置界面所示,就是多个section;微信就是一个section。

我们使用viewController操作UITableView时,需要实现下面的协议

MVC模式在UITableView视图中得到了充分体现,viewController通过实现UITableViewDataSource协议进行model的访问,如获取section数,获取给定section的cell数等等,model中定义了cell的相关数据,该协议有两个@required方法

@protocol UITableViewDataSource

@required

//将tableview的给定组(Section)的行(cell)数从DataSource中读取返回
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;

//访问DataSource中indexPath的cell数据来创建并返回一个cell
- (UITableViewCell *)tableView:(UITableView *)tableView 
    cellForRowAtIndexPath:(NSIndexPath *)indexPath;

@optional

我们在VC中创建示例代码如下

#import "ViewController.h"

@interface ViewController ()
@property (strong,nonatomic) UITableView * tab;
@property (strong,nonatomic) NSMutableArray * arrySource;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //创建UITableView,设置委托及DataSource
    _tab = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tab.dataSource = self;
    _tab.delegate = self;
    [self.view addSubview:_tab];
    
    //修改DataSource内容
    _arrySource = [[NSMutableArray alloc] init];
    for(NSUInteger i = 0;i < 3;i++){
        NSMutableArray * cellCount = [[NSMutableArray alloc] init];
        for(NSUInteger j = 0;j < 4;j++)
        {
            NSString * str = [[NSString alloc]initWithFormat:@"%ld组,%ld行",i,j];
            [cellCount addObject:str];
        }
        [_arrySource addObject: cellCount];
    }
}

//section的cell数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[_arrySource objectAtIndex:section] count];
}

//optional,返回tableView的section数,没有实现则为1
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_arrySource count];
}

//创建单元格
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * celStr = @"cell";
    //尝试获取可以复用的单元格
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:celStr];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:celStr];
        
    }
    NSString * cellTextLable = [[_arrySource objectAtIndex: indexPath.section] objectAtIndex:indexPath.row];
    cell.textLabel.text = cellTextLable;
    return cell;
}


@end

即可显示出一个三组四行元素的table view,如下图所示,实现协议中其他optional方法可以对tableview进行更多操作,详情请见UIKit的documentation,其中的dequeueReusableCellWithIdentifier是处于性能考虑,在滚动时新出现的cell尝试复用不会显示的cell来节省内存,提高性能。

Tabview示例

【UITableViewDelegate】

【UITableViewDataSource】

1.2.UITableView的UITableViewCell及相关属性

UITableViewCell作为UITableView的显示内容,其主要有一个UIView控件(contentView,作为其他元素的父控件)、两个UILable控件(textLabel、detailTextLabel)、一个UIImage控件(imageView),分别用于容器、显示内容、详情和图片。具体如同微信、QQ的消息界面,上面的微信界面图即是示例。

UITableViewCell

通过UITableViewCellStyle可以设置UITableViewCell的风格,具体如下

typedef NS_ENUM(NSInteger, UITableViewCellStyle) {
    UITableViewCellStyleDefault,    
    //左侧显示textLabel(不显示detailTextLabel),imageView可选
    
    UITableViewCellStyleValue1,     
    //左侧显示textLabel、右侧显示detailTextLabel(默认蓝色),imageView可选(显示在最左边)
    
    UITableViewCellStyleValue2,     
    //左侧依次显示textLabel(默认蓝色)和detailTextLabel,imageView可选(显示在最左边)
    
    UITableViewCellStyleSubtitle    
    //左上方显示textLabel,左下方显示detailTextLabel(默认灰色),imageView可选(显示在最左边)
            
}; 

相关代码

//获取cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{   
    NSString * celStr = @"cell";
    //cell复用
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:celStr];   
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:celStr];
    }
   
    //imageview
    UIImage *img = [UIImage imageNamed:@"12.jpg"];
    [cell.imageView setImage: img];
    [cell.imageView setHighlightedImage:img];
    
    //texLable与detailLable
    cell.textLabel.text = @"xxx";
    cell.detailTextLabel.text = @"xxx";
    
    return cell;
}

除了这四个view,cell中还有accessoryView 等其他view,如设置界面右侧的图标(iOS称之为访问器),通过UITableViewCell的accesoryType属性可以设置为系统提供的几个图标,也可以在创建cell时将一个一个UIView对象指针赋值给cell.accessoryView属性来显示自定义的图标。

typedef NS_ENUM(NSInteger, UITableViewCellAccessoryType) {
    UITableViewCellAccessoryNone,                   // 不显示任何图标
    UITableViewCellAccessoryDisclosureIndicator,    // 跳转指示图标
    UITableViewCellAccessoryDetailDisclosureButton, // 内容详情图标和跳转指示图标
    UITableViewCellAccessoryCheckmark,              // 勾选图标
    UITableViewCellAccessoryDetailButton NS_ENUM_AVAILABLE_IOS(7_0) // 内容详情图标
};

相关代码

[cell setAccessoryType:UITableViewCellAccessoryDetailDisclosureButton];

做一个示例代码如下来展示cell内部的几个subview内容:

#import "ViewController.h"

@interface ViewController ()
@property (strong,nonatomic) UITableView * tab;
@property (strong,nonatomic) NSMutableArray * arrySource;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _tab = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];

    _tab.dataSource = self;
    _tab.delegate = self;
    [self.view addSubview:_tab];
    _arrySource = [[NSMutableArray alloc] init];
    for(NSUInteger i = 0;i < 3;i++){
        NSMutableArray * cellCount = [[NSMutableArray alloc] init];
        for(NSUInteger j = 0;j < 4;j++)
        {
            NSString * str = [[NSString alloc]initWithFormat:@"%ld组,%ld行",i,j];
            [cellCount addObject:str];
        }
        [_arrySource addObject: cellCount];
    }
}

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

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_arrySource count];
}

//获取cell内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * celStr = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:celStr];
    
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:celStr];
    }
    UIImage *img = [UIImage imageNamed:@"12.jpg"];
    
    [cell.imageView setImage: img];
    [cell.imageView setHighlightedImage:img];
    
    
    [cell setAccessoryType:UITableViewCellAccessoryDetailDisclosureButton];
    
    NSString * cellTextLable = [[_arrySource objectAtIndex: indexPath.section] objectAtIndex:indexPath.row];
    cell.textLabel.text = cellTextLable;
    cell.detailTextLabel.text = @"嘻嘻嘻";
    return cell;
}
@end

运行结果界面如下,左侧显示textLabel、右侧显示detailTextLabel,右侧显示了内容详情图标和跳转指示图标。tabBar可以忽略下。

cell的content

1.2.UITableView协议常用方法

1.UITableViewDataSource 协议
#pragma mark 返回每组头标题名称
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return [NSString stringWithFormat:@"第%li组头部",section];
}

#pragma mark 返回每组尾部说明
-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
    return [NSString stringWithFormat:@"第%li组尾部",section];
}

#pragma mark 设置分组头部标题内容高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section==0){
        return 50;
    }
    return 20;
}

#pragma mark 设置每行高度(每行高度可以不一样)
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

#pragma mark 设置尾部说明内容高度
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 40;
}
2.UITableViewDelegate 协议
#pragma mark 选中行
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"%li组 %li行",indexPath.section,indexPath.row);
}

#pragma mark 编辑状态下根据editingStyle(添加/删除)操作调用,编辑状态进行提交
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_arrySource[indexPath.section] removeObjectAtIndex:indexPath.row];
    [_tab reloadData];
}
编辑单元格

1.3UITableViewCell自定义

一般实现自定义UITableViewCell需要分为两步:第一初始化控件;第二设置数据,重新设置控件frame。原因就是自定义Cell一般无法固定高度,很多时候高度需要随着内容改变。此外由于在单元格内部是无法控制单元格高度的,因此一般会定义一个高度属性用于在UITableView的代理事件中设置每个单元格高度。

具体见【自定义Cell】

1.4性能相关

1.局部刷新

当对DataSource操作后更新view,上文使用了

[_tab reloadData];

全部刷新是非常耗费性能的,尤其当我们的tableview有大量cell时候,我们一般采用局部刷新

//刷新表格
NSArray *indexPaths=@[_selectedIndexPath];
//需要局部刷新的单元格的组、行
[_tab reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft];
//后面的参数代表更新时的动画
2.cell复用

显示界面有限,而cell可能有非常多,复用cell非常有必要,用一个NSString的标识标识不同的cell,进行复用

NSString * celStr = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:celStr];
    
if(cell == nil)
{
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:celStr];
}

**-(UITableViewCell *)tableView:(UITableView )tableView cellForRowAtIndexPath:(NSIndexPath )方法调用很频繁,无论是初始化、上下滚动、刷新都会调用此方法,所有在这里执行的操作一定要注意性能;

2.UICollectionView的使用


UICollectionView与UITableView在一定程度上很相似,较大的区别是UICollectionView必须自定义cell。其常用于来实现瀑布流,使用UICollectionView需要实现下面三个协议,较之UITableView多一个布局的协议。

见下篇

你可能感兴趣的:(2018-06-12)