UITableView的创建与使用

1,表视图的创建

表视图可以用UITableViewController来创建,表格控制器默认的根视图就是一个表视图
     这里主要介绍表视图在视图控制器(ViewController)中创建 ,创建方法:

UITableView *tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 20, 375, 647) style:UITableViewStyleGrouped];
//设置代理 
tableView.delegate = self;
tableView.dataSource = self;
//添加到当前视图上    
[self.view addSubview:tableView];
 
 
表视图初始化的时候,样式有两种,平铺样式和分组样式UITableViewStyleGrouped 分组样式
UITableViewStylePlain 平铺样式
2,必须实现的代理方法<UITableViewDelegate,UITableViewDataSource>
//此方法返回每组单元格的个数(确定要创建多少单元格)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{    
    return fontNames.count;
}
//返回值为cell,此代理方法是用来创建单元格
参数indexPath有两个属性:
indexPath.section表示是哪一组
indexPath.row表示是哪一行
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //创建单元格
}

3, 创建单元格cell的方法

在创建单元格的时候有两种方法创建:(1)从闲置池去单元格,起到懒加载作用.(2)注册单元格

<1>,从闲置池取单元格(当闲置池有空闲的单元格的时候,就从闲置池取,闲置池没有的时候再创建单元格)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];   
    }
    NSArray *fontNames=[dataList objectAtIndex:indexPath.section];
    NSString *font=[fontNames objectAtIndex:indexPath.row];
    cell.textLabel.text=font;
    cell.textLabel.font=[UIFont fontWithName:font size:20];
    return cell;
}
<2>注册单元格(在创建的时候就注册,不在代理方法里注册)

 //这句代码是在创建之后写的,不是在代理方法中写
[tableView registerClass:[UITableViewCell class]forCellReuseIdentifier:@"cell"];

 //在代理方法中直接取单元格,不需要创建
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"" forIndexPath:indexPath];
   NSArray *fontNames=[dataList objectAtIndex:indexPath.section];
   NSString *font=[fontNames objectAtIndex:indexPath.row];
   cell.textLabel.text=font;
   cell.textLabel.font=[UIFont fontWithName:font size:20];
   return cell;
}

注意:如果是用xib文件画出来的单元格时,注册要用下面的方法

[tableView registerNib:[UINib nibWithNibName:@"NIbCell" bundle:nil] forCellReuseIdentifier:iden];

3,设置单元格的高度,两种方法
//(1),直接在创建tableView的时候用tableView来设置
tableView.rowHeight = 100;
//2,用tableView的代理方法设置单元格的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath




4,常用的代理方法
//此方法是设置每一组的组标题,有多少组就调用多少次
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
   NSString *headerTitle=[NSString stringWithFormat:@"第%ld组",section+1];
   return headerTitle;
}
由于代理方法太多,这里就不一一细说了,各位在使用的时候点进代理方法看看,选择自己需要的方法,主要是能灵活运用
















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值