现在的位置: 首页 > 综合 > 正文

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

2018年05月28日 ⁄ 综合 ⁄ 共 1706字 ⁄ 字号 评论关闭

【本文来自blog.csdn.net/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

抱歉!评论已关闭.