ios表视图控制器

表视图

数据一列多行的列表形式展示数据的一种视图UITableView,父类是UIScrollView优势:无需计算每行的坐标,只需要关注每行的数据如何展示以及数据是什么就可以了

  • 如何使用表视图?
    表视图有两个重要的属性,一个叫dataSource,一个叫delegate。其实两个都是表视图的代理,dataSource代理负责表格要显示数据来源,delegate负责表格与用户的交互响应即表格的自定义样式。其中dataSource必须设置
    步骤:

step1:设置表格的dataSource数据源代理为当前控制器
step2:让当前控制器遵守UITableViewDataSource协议
step3:实现方法
方法一:表格有几个分区numberOfSectionsInTableView
方法二:每个分区有几行numberOfRowsInSection
方法三:每行的内容什么样cellForRowAtIndexPath
MyViewController.m

#import "MyViewController.h"
@interface MyViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)UITableView *tableView;
@end
@implementation MyViewController
#pragma mark - 以下是tableView数据源的代理方法 TableView DataSource
//设置分区头
//问一:有多少个分区(可选则实现代理方法, 如果不实现默认是1分区)
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
//问二:每个分区有多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0) return 5;
    if(section == 1) return 10;
    return 8;
}
//问三:每行长什么样子
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //当前的分区号
    NSInteger section = indexPath.section;
    //当前是第几行
    NSInteger row = indexPath.row;
    UITableViewCell *cell = [[UITableViewCell alloc]init];
    cell.textLabel.text = [NSString stringWithFormat: @"这是第%ld个分区,这是第%ld个单元格",section,row];
    return cell;
}
//设置分区头文本的 数据源代理方法 nullable可以返回字符串空
//- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{   // fixed font style. use custom view (UILabel) if you want something different
//    return [NSString stringWithFormat:@"这是第%ld个分区 分区头",section];
//
//}
//设置分区尾文本的 数据源代理方法
//- (nullable NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
//    return [NSString stringWithFormat:@"这是第%ld个分区 分区尾",section];
//}
#pragma mark - 以下TableView Datagate 的代理方法
//设置分区头的高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 60;
}
//设置分区头视图(自定义分区头 一定要设置分区头高度)
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 40)];
    label.backgroundColor = [UIColor yellowColor];
    label.text = [NSString stringWithFormat:@"%ld分区",section];
    label.textAlignment = NSTextAlignmentCenter;
    return label;
}
- (void)viewDidLoad {
    [super viewDidLoad];
   self.tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    //设置tableView的数据源
    self.tableView.dataSource =self;
    //设置tableView的代理
    self.tableView.delegate = self;
    //表头和表尾 只能通过属性 来完成设置
    //表头
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 200)];
    imageView.image = [UIImage imageNamed:@"timg2"];
    self.tableView.tableHeaderView =imageView;
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(0, 0, self.tableView.frame.size.width, 40);
    [button setTitle:@"加载更多内容" forState:UIControlStateNormal];
    button.backgroundColor =[UIColor colorWithRed:0 green:0.5 blue:1 alpha:1];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:24];
    self.tableView.tableFooterView = button;
    [self.view addSubview:self.tableView];
}
  • 单元格重用

将那些已经滚动出屏幕以外的cell对象,能够取回来,修改一下上面显示的文字,再重新放到表格的可见区域,用于展示数据

  • 系统已经为我们做了哪些事情?
    系统会自动将那些已经完整的超出屏幕的cell对象,自动放在一个队列中存储起来
    解决方案一:
    进到第三个方法后,不要着急立即新建cell,而是先去队列中尝试着去取,看有没有已经被回收了的cell对象
    如果能够取到cell,则直接修改cell中的内容,然后返回即可
    如果取不到cell,再新建cell对象,然后返回
//问三:每行长什么样子
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //当前的分区号
    NSInteger section = indexPath.section;
    //当前是第几行
    NSInteger row = indexPath.row;
    //从tableView的空闲队列中 取出名字叫 张三的 单元格
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"张三"];
    if(!cell){
        static int index = 0;
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"张三"];
        index++;
        NSLog(@"创建了%d个",index);
    }
        
    cell.textLabel.text = [NSString stringWithFormat: @"这是第%ld个分区,这是第%ld个单元格",section,row];
    return cell;
}

解决方案二:
提前将单元格德类型注册一下,即让系统tableView记录一下单元格类的信息,然后,回答第三问,再去dequeque取可重用单元格时,如果没有取到,则有系统根据提前注册的类型,为我们自动新建一个cell对象。
这样,保证在dequeque之后,一定会有一个cell对象,我们不关注这个对象是旧的,还是系统为我们自动创建的cell.直接赋值显示,返回即可。
MyViewController.m

import "MyViewController.h"
@interface MyViewController ()<UITableViewDataSource>
@end
@implementation MyViewController
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 40;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //从tabelView 队列中 取空闲cell,如果没有取到有tableView根据我之前注册的cell类,来帮我创建一个cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"张三" forIndexPath:indexPath];
    cell.textLabel.text = @"abc";
    return cell;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    UITableView *tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    tableView.dataSource =self;
    //向tableView 注册一个 cell 类的样式,在复用时会根据这个注册的来创建cell对象
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"张三"];
    [self.view addSubview:tableView];
}

UITableViewController表视图控制器

天生自带一个tableView类型的视图,并且当前控制器已经被设置成为这个tableView的数据源即delegate代理。同时,控制器也已经遵守UITableViewDataSource及UITableViewDelegate协议

  • 如何使用?
    编写一个类,继承自UITableViewController,然后只需要关注三问,完成数据的显示即可。

UITableViewCell

左边叫内容视图contenView,右边叫辅助视图accessoryView

  • 内容视图
    系统版:cell内部天生就有三个子控件,为两个标签一个图片框,直接赋值显示即可,无需创建添加contentView中
    通过textLabel和datailTextLabel访问两个标签,通过imageView属性访问图片框。
    系统还提供了四种摆放三个子视图的方式。通过在创建cell对象实例时的style参数可以决定三个视图如何摆放
    syle:default,value1,value2,subtitle
    default:只有图片+textLabel
    value1:也叫right右对齐,detail在右侧
    value2:也叫left左对齐,detail在左侧
    subtitle:三个都可见,detail在下侧
  • 辅助视图
    系统版:
    通过给accessoryType属性即可。一共四种选择,checkmark对勾样式,disclosure大于号样式,detail圆圈I样式,detail+disclosure既有大于号又有圆圈i
    自定义版:通过给accessoryView属性一个视图对象即可。
    MyTableViewController.m
#import "MyTableViewController.h"
@interface MyTableViewController ()
@end
@implementation MyTableViewController
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 40;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"张三"];
    if(!cell){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"张三"];
    }
    //设置内容视图
//    cell.textLabel.text = @"标题";
//    cell.detailTextLabel.text = @"详细";
//    cell.imageView.image = [UIImage imageNamed:@"timg5"];
    
    UILabel *label = [cell.contentView viewWithTag:100];
    if(!label){
        label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, cell.contentView.frame.size.width,80)];
        label.tag = 100;
        label.font = [UIFont systemFontOfSize:36];
        label.textAlignment =NSTextAlignmentCenter;
        [cell.contentView addSubview:label];
    }
    label.text = [NSString stringWithFormat:@"第%ld行",indexPath.row];
    //设置系统版辅助视图
//    UITableViewCellAccessoryNone
//    UITableViewCellAccessoryDisclosureIndicator 大于号
//    UITableViewCellAccessoryDetailDisclosureButton 圈i加大于号
//    UITableViewCellAccessoryCheckmark 对勾
//    UITableViewCellAccessoryDetailButton 圈i
    if(indexPath.row != 1)
    {
        cell.accessoryView = nil;
        cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    }else{
        UISwitch *mySwitch = [[UISwitch alloc]init];
        cell.accessoryView = mySwitch;
    }
    return cell;
 }
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    return 80;
}

封装图片滚动视图

HeaderView.h

#import <UIKit/UIKit.h>
@class HeaderView;
@protocol HeadViewDelegate <NSObject>
-(void)headerView:(HeaderView*)headerView didTapPageNum:(NSInteger)pageNum;
@end
@interface HeaderView : UIView
-(instancetype)initWithImageNameArray:(NSArray*)imageNames frame:(CGRect)frame;
@property(nonatomic,strong)id<HeadViewDelegate>delegate;
@end

HeaderView.m

#import "HeaderView.h"
@interface HeaderView ()<UIScrollViewDelegate>
@property(nonatomic,strong)UIScrollView *sv;
@property(nonatomic,strong)UIPageControl *pageControl;
@property(nonatomic,strong)NSArray *imageArray;
@end
@implementation HeaderView
-(instancetype)initWithImageNameArray:(NSArray*)imageNames frame:(CGRect)frame{
    if(self = [super initWithFrame:frame]){
        self.imageArray = imageNames;
        [self sv];
        [self pageControl];
    }
    return self;
}
-(instancetype)initWithFrame:(CGRect)frame{
    if(self = [super initWithFrame:frame]){
        [self sv];
        [self pageControl];
    }
    return self;
    
}
-(UIPageControl *)pageControl
{
    if(!_pageControl){
        _pageControl = [[UIPageControl alloc]init];
        _pageControl.frame = CGRectMake(0, self.frame.size.height-20-40, self.frame.size.width, 40);
        _pageControl.numberOfPages = self.imageArray.count;
        _pageControl.currentPage = 0;
        //设置当前选中的颜色
        [_pageControl setPageIndicatorTintColor:[UIColor redColor]];
        //设置其他未选中的颜色
        [_pageControl setPageIndicatorTintColor:[UIColor greenColor]];
        [self addSubview:_pageControl];
        _pageControl.enabled = NO;
    }
    return _pageControl;
}
-(void)tap:(UITapGestureRecognizer*)sender{
    NSInteger pageNum =self.pageControl.currentPage;
    [self.delegate headerView:self didTapPageNum:pageNum];
}
//懒加载
-(UIScrollView *)sv
{
    if(!_sv)
    {
        _sv = [[UIScrollView alloc]init];
        _sv.delegate = self;
        _sv.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        _sv.contentSize= CGSizeMake(self.frame.size.width * self.imageArray.count, self.frame.size.height);
        for(NSInteger i = 0; i<self.imageArray.count;i++)
        {
            UIImageView *iv = [[UIImageView alloc]initWithFrame:CGRectMake(self.frame.size.width * i, 0, self.frame.size.width, self.frame.size.height)];
            NSString *imageName =self.imageArray[i];
            iv.image = [UIImage imageNamed:imageName];
            [_sv addSubview:iv];
        }
        //隐藏水平滚动条
        _sv.showsVerticalScrollIndicator = NO;
        //取消弹性效果
        _sv.bounces = NO;
        //设置整屏滑动 是针对 frame来说的
        _sv.pagingEnabled = YES;
        [self addSubview:_sv];
        //给scrollView添加点击手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
        [_sv addGestureRecognizer:tap];
    }
    return  _sv;
}
//实现代理方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //round c 的四舍五入
    NSInteger page =  round(scrollView.contentOffset.x / self.frame.size.width);
    self.pageControl.currentPage = page;
}
@end

ViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    HeaderView *hv1 = [[HeaderView alloc]initWithImageNameArray:@[@"timg",@"timg1",@"timg3",@"timg5",@"psc"] frame:CGRectMake(50, 50, 300, 200)];
    [self.view addSubview:hv1];
    HeaderView *hv2 = [[HeaderView alloc]initWithImageNameArray:@[@"timg3",@"psc"] frame:CGRectMake(50, 500, 300, 200)];
    [self.view addSubview:hv2];
    HeaderView *hv3 = [[HeaderView alloc]initWithImageNameArray:@[@"timg1",@"timg5"] frame:CGRectMake(50, 300, 300, 100)];
    [self.view addSubview:hv3];
}

MyViewController.m

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