如何在一个string中获取UITableView的选定单元格的值

我很确定这很简单。 但是我不能做这个工作。 我有一个UITableView,我dynamic显示一个Facebook的朋友列表,感谢他们的FBID。 基本上,我想返回我select的朋友的FBID,用逗号分隔的一个string。 如果可能的话,在一个IBAction中,所以我可以将它们传递给一个php的参数。 例如,让我们假装我有一个4个朋友的名单,ABCD,他们的ID是1,2,3,4。 如果我selectA和C,我想有一个string,说1,3。

所有我设法做的是显示我select的朋友的ID,一次一个。 这是我的代码:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { rowcount = [[tableView indexPathsForSelectedRows] count]; indexer = [idFriends objectAtIndex:indexPath.row]; aapell = [NSString stringWithFormat:@"%@", indexer]; NSMutableString * arrayIds = [[NSMutableString alloc] init]; [arrayIds appendString:aapell]; NSLog(@"ids: %@", arrayIds); } 

预先感谢您,我确信这并不复杂。

 -(IBAction)gatherFBIds { NSString *listOfFacebookIDs = @""; NSArray *indexPathArray = [self.tableView indexPathsForSelectedRows]; for(NSIndexPath *index in indexPathArray) { //Assuming that 'idFriends' is an array you've made containing the id's (and in the same order as your tableview) //Otherwise embed the ID as a property of a custom tableViewCell and access directly from the cell //Also assuming you only have one section inside your tableview NSString *fbID = [idFriends objectAtIndex:index.row]; if([indexPathArray lastObject]!=index) { listOfFacebookIDs = [listOfFacebookIDs stringByAppendingString:[fbID stringByAppendingString:@", "]]; } else { listOfFacebookIDs = [listOfFacebookIDs stringByAppendingString:fbID]; } } NSLog(@"Your comma separated string is %@",listOfFacebookIDs); //Now pass this list to wherever you'd like } 

问题是你没有使用indexPathsForSelectedRows的信息。 这是告诉你所有选定的行。 相反,你只是看着indexPath.row ,这是最近select的一行。

你需要做的是循环遍历indexPathsForSelectedRows并收集当前选中的每一行的信息(我假设你在这里启用了多个select)。

  Use the following code to get the selected rows in a table view. :) NSArray *selectedRows=[tableView indexPathsForSelectedRows]; NSMutableArray *rownumberArray=[[NSMutableArray alloc]init]; for (int i=0; i<selectedRows.count; i++) { NSIndexPath *indexPath = [selectedRows objectAtIndex:i]; NSInteger row = indexPath.row; NSNumber *number = [NSNumber numberWithInteger:row]; [rownumberArray addObject:number]; } // rownumberArray contains the row numbers of selected cells.