用不同的单元格types创build分组的UITableview

我需要创build一个分组的可视化视图,其中包括一些部分和每个部分中可能不同的单元格types。

我试图创build像旧的Foursquare应用程序,用户页面(包括“排行榜”,“朋友build议”,“朋友”,“统计”,“最探究的类别”…部分)的东西。

我对ios编程相当陌生,所以这个视图可能不是一个分组的可视视图。

我特别坚持的是为部分创build不同的单元格,并找出哪些单元格被点击。

我的数据源将是由不同的数据types组成的2个不同的NSArray *,这就是为什么我需要不同的自定义单元格。

既然你有两组不同的数据,你需要在不同的部分显示,你必须将数据源方法分成两部分。

基本上,select你想成为第一个数据集,然后离开你。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if(section)return secondArray.count; //Essentially, if statements evaluate TRUE and move forward if the inside is 1 or greater (TRUE == 1) return firstArray.count; //If the first if statement return hits, then the code will never reach this statement which turns this into a lighter if else statement } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { if(indexPath.section) { //do stuff with second array and choose cell type x } else { //do stuff with first array and choose cell type y } } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { //Get the cell with: UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; if(indexPath.section) { //perform action for second dataset } else { //perform action for first dataset } } 

对于标题,您可以使用这些方法中的任何一种,只保留与上面相同types的样式:

 - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section; - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section; 

您可以创buildUITableViewCell的多个自定义子类,并在您的UITableViewDataSource的tableView:cellForRowAtIndexPath:方法中,可以使用if语句来确定要使用的单元types。

例如,下面是我可能做的一个粗略的概述:

 -(UITableViewCell *)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //First, determine what type of object we're showing if (indexPath.section == 0) { //Create and return this cell. } else if (indexPath.section == 1) { //Create and return this cell. }... } 

以下是你如何实现numberOfRowsInSection

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (section == 0) { return [firstSectionArray count]; } else if (section == 1) { return [secondSectionArray count]; } ... } 

对于didSelectRowAtIndexPath

 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.section == 0) { ObjectSelected *objectSelected = [firstArray objectAtIndex:indexPath.row]; //Now you've got the object, so push a view controller: DetailViewController *dvc = [[DetailViewController alloc] init]; dvc.objectSelected = objectSelected; [self.navigationController pushViewController:dvc]; } else if (indexPath.section == 1) { //Same thing, just call [secondArray objectAtIndex:indexPath.row] instead! } }