iPhone tableview分批显示数据

iPhone屏幕尺寸是有限的,如果需要显示的数据很多,可以先数据放到 一个table中,先显示10条,table底部有一察看更多选项,点击察 看更多查看解析的剩余数据。基本上就是数据源里先只放10条, 点击最后一个cell时, 添加更多的数据到数据源中. 比如:

数据源是个array:

NSMutableArray *items;
ViewController的这个方法返回数据条数: +1是为了显示"加载更多"的那个cell
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        int count = [items count];
    return  count + 1;
}

  这个方法定制cell的显示, 尤其是"加载更多"的那个cell:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if([indexPath row] == ([items count])) {
        //创建loadMoreCell
        return loadMoreCell;
    }
    
    //create your data cell

    return cell;
}

  还要处理"加载更多"的那个cell的选择事件,触发一个方法来加载更多数据到列表

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == [items count]) {
        [loadMoreCell setDisplayText:@"loading more ..."];
        [loadMoreCell setAnimating:YES];
        [self performSelectorInBackground:@selector(loadMore) withObject:nil];
        //[loadMoreCell setHighlighted:NO];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        return;
    }

    //其他cell的事件
     
}

  加载数据的方法:

-(void)loadMore
{
    NSMutableArray *more; 
        //加载你的数据
    [self performSelectorOnMainThread:@selector(appendTableWith:) withObject:more waitUntilDone:NO];
}

  添加数据到列表:

-(void) appendTableWith:(NSMutableArray *)data
{

    for (int i=0;i<[data count];i++) {
        [items addObject:[data objectAtIndex:i]];
    }
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:10];
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath    *newPath =  [NSIndexPath indexPathForRow:[items indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    [self.tableView insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];

}

 

/////////////////////////////////////////////////////////////////////////////

 

NSIndexPath是一種特別的資料類別,這是用來表示一個路徑,這個路徑是指到一個從0開始的巢狀集合陣列樹狀結構的某個節點。iPhone OS為UITableView擴充了這個類別(見NSIndexPath UIKit Additions這 是用分類擴充),加入了一個用來建立新的NSIndexPath實體的「(NSIndexPath *)indexPathForRow:(NSUInteger)row inSection:(NSUInteger)section」方法和row和section兩個屬性。
 
如果你想要新增資料:需要透過「indexPathForRow:  inSection:」方法來建立indexPath,然後呼叫tableView的「insertRowsAtIndexPaths:withRowAnimation:」來新增。
 
如果你要更新資料:需要透過「indexPathForRow:  inSection:」方法來建立indexPath,然後呼叫tableView的「reloadRowsAtIndexPaths:withRowAnimation:」來更新。
 
如果你要刪除資料:需要透過「indexPathForRow:  inSection:」方法來建立indexPath,然後呼叫tableView的「deselectRowAtIndexPath:animated:」來刪除。
 
所以,想要操控好表格視圖,懂得NSIndexPath和建立它的「indexPathForRow:  inSection:」方法,就是非常重要的。

posted on 2012-11-15 18:12  无量少年  阅读(387)  评论(0)    收藏  举报

导航