iOS,UITableView详细介绍之基本使用(一)

iOS中,UITableVIew的使用是非常常见的,下面就来详细介绍一下

1.UITableView必须实现两个代理:UITableVIewDataSource,UITableViewDelegate

2.UITableView的三个关键代理方法是:

    (1)-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

     (2)-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

     (3)-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

 3.下面以一个最基本的例子来详细介绍UITableVIew的使用

代码如下:

#import "ViewController.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)UITableView *tableView;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //创建一个UITableView
    UITableView *tableView=[[UITableView alloc]init];
    tableView.frame=CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    //设置代理方法
    tableView.delegate=self;
    //设置数据源
    tableView.dataSource=self;
    
    self.tableView=tableView;
    [self.view addSubview:tableView];
    
    //如果不想要系统自带的下划线
    //self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    
}

//有几个部分
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//每一部分有几条数据
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 10;
}
//每一数据的具体显示
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //设定一个标志,用于cell的重用的,滑出视觉范围的cell会被放入空闲队列而不是被销毁,提高性能了。
    static NSString *cellId=@"cellId";
    //从空闲队列里取出一个cell
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellId];
    //如果为空,就新建
    if(!cell)
    {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
    }
    //cell的一些具体展示
    cell.textLabel.text=[NSString stringWithFormat:@"%ld",indexPath.row+1];
    cell.imageView.image=[UIImage imageNamed:@"111"];
    cell.detailTextLabel.text=@"小悦悦";
    
    //如果想要系统自带的箭头
    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

//设置每一行cell的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

//每一行点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"====%ld",indexPath.row);
}

//设置header文字
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"生活";
}

4.效果图:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值