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.效果图: