詳解iPhone Tableview分批顯示數據 實現點擊加載更多
其實這個實現起來,開始是啥思路也木有的,但是明白了之後,其實很簡單的。
iPhone屏幕尺寸是有限的,如果需要顯示的數據很多,可以先數據放到一個table中,先顯示10條,table底部有一察看更多選項,點擊察看更多查看解析的剩餘數據。基本上就是數據源裏先只放10條, 點擊最後一個cell時, 添加更多的數據到數據源中. 比如:
數據源是個array:
NSMutableArray *items;
ViewController的這個方法返回數據條數: +1是爲了顯示"加載更多"的那個cell
1
2
3
4
5
|
- (NSInteger)tableViewUITableView *)tableView numberOfRowsInSectionNSInteger)section { int count = [items count]; return count + 1; } |
這個方法定製cell的顯示, 尤其是"加載更多"的那個cell:
1
2
3
4
5
6
7
8
9
|
- (UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath { if ([indexPath row] == ([items count])) { //創建loadMoreCell return loadMoreCell; } //create your data cell return cell; } |
還要處理"加載更多"的那個cell的選擇事件,觸發一個方法來加載更多數據到列表
1
2
3
4
5
6
7
8
9
10
11
12
13
|
- ( void )tableViewUITableView *)tableView didSelectRowAtIndexPathNSIndexPath *)indexPath { if (indexPath.row == [items count]) { [loadMoreCell setDisplayText:@ "loading more ..." ]; [loadMoreCell setAnimating:YES]; [self performSelectorInBackgroundselector(loadMore) withObject:nil]; //[loadMoreCell setHighlighted:NO]; [tableView deselectRowAtIndexPath:indexPath animated:YES]; return ; } //其他cell的事件 } |
加載數據的方法:
1
2
3
4
5
6
|
-( void )loadMore { NSMutableArray *more; //加載你的數據 [self performSelectorOnMainThreadselector(appendTableWith withObject:more waitUntilDone:NO]; } |
添加數據到列表:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
-( void ) appendTableWithNSMutableArray *)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]; } |