iOS的 TableView 的简单用法1 - 实现数据源

本文详细介绍了在iOS开发中使用TableViewController展示和管理数据的步骤,包括Storyboard配置、数据源实现、解析tableView函数及理解Section与Cell的概念。通过实践案例,帮助开发者快速掌握TableViewController的基本用法。

【本文来自blog.youkuaiyun.com/lanmanck】

新建TableViewController和关联的类就不说了。

要显示Cell数据,做如下几步骤:

1、在Storyboard点击单个Cell,在Attributor Inspector的Identifier设置好,Accessory也设置好,例如设为Disclosure Indicator

2、在ApplicationDelegate.m里实现数据源,如果TableView有多个Section就搞多个数据源,参考博客:

iOS Storyboard 初探(三)

3、在TableViewController的实现文件中重载TableView的函数,解析如下:

设置Section个数:

//返回tableview的章节数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 2;
}
设置每个Section的Cell数:

//返回数组个数,指定显示多少cell
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    //根据不同的section数值返回不同的count
    if(section == 1)
        return [self.playersArray2 count];
    else
        return [self.playersArray count];
}
设置要显示的数据:

//indexPath标示的是你要渲染的这个cell的位置,indexPath对象里有两个属性,section和row,顾名思义,可以定位某个cell。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    
    if(indexPath.section == 0){
        //这个匹配的字符串要在attributor inspector中的accessory设置
        cell = [tableView dequeueReusableCellWithIdentifier:@"PlayerCell"];
    
        // Configure the cell...
        if(cell !=nil){
            DGPlayer *player = [self.playersArray objectAtIndex:indexPath.row]; //找到数组下标
            cell.textLabel.text = player.name; //赋值给当前的cell
            cell.detailTextLabel.text = player.game;
        }
    }else{
        //这个匹配的字符串要在attributor inspector中的accessory设置
        cell = [tableView dequeueReusableCellWithIdentifier:@"PlayerCell2"];
        
        // Configure the cell...
        if(cell !=nil){
            DGPlayer *player = [self.playersArray2 objectAtIndex:indexPath.row]; //找到数组下标
            cell.textLabel.text = player.name; //赋值给当前的cell
            cell.detailTextLabel.text = player.game;
        }
    }
    
    return cell;
}

4、何为Section和Cell?看下这个链接,图文并茂:

http://segmentfault.com/q/1010000000095547





评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值