我按照我在网上找到的教程创建了一个表格视图,其中包含自定义对象数组中的部分和索引。此代码的工作原理是,当我在表中选择一行时,我是该部分的索引路径,而不是整个数组的索引路径。我知道为什么它不起作用,但我不知道如何解决这个问题,这是我的表格视图代码单元格。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"NameCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure the cell...
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int displayOrder = [defaults integerForKey:@"displayOrder"];
int sortOrder = [defaults integerForKey:@"sortOrder"];
NSString *alphabet = [listIndex objectAtIndex:[indexPath section]];
NSPredicate *sectionPredicate = [[NSPredicate alloc] init];
if (sortOrder == 1) {
//NSLog(@"fName is predicate at cell level");
sectionPredicate = [NSPredicate predicateWithFormat:@"fName beginswith[c] %@", alphabet];
} else {
//NSLog(@"lName is predicate at cell level");
sectionPredicate = [NSPredicate predicateWithFormat:@"lName beginswith[c] %@", alphabet];
}
NSArray *sectionContacts = [filteredList filteredArrayUsingPredicate:sectionPredicate];
if (isSearching) {
current = [filteredList objectAtIndex:indexPath.row];
} else{
current = [sectionContacts objectAtIndex:indexPath.row];
}
if (displayOrder == 1) {
NSString *fullName = [NSString stringWithFormat:@"%@ %@",[current valueForKey:@"fName"],[current valueForKey:@"lName"]];
[cell.textLabel setText:fullName];
//NSLog(@"FirstNameFirst");
} else {
NSString *fullName = [NSString stringWithFormat:@"%@ %@",[current valueForKey:@"lName"],[current valueForKey:@"fName"]];
[cell.textLabel setText:fullName];
//NSLog(@"LastNameFirst");
}
[cell.detailTextLabel setText:[current valueForKey:@"extension"]];
return cell; }
然后我用这段代码调用 segue。
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:@"showContact"]) {
DetailViewController *dvc = [segue destinationViewController];
NSIndexPath *path = [self.tableView indexPathForSelectedRow];
NSDictionary *c = [filteredList objectAtIndex:path.row];
[dvc setCurrentContact:c];
[searchBar resignFirstResponder];
} }
问题是 objectAtIndex:path.row 返回该部分的索引,但并未针对整个数组进行修改,因此如果点击该部分索引 4 处的“B”部分中的名称,它会返回主数组索引 4 处的对象。我一直在摸索如何获取完整数组的索引,而不是仅在该部分本地的索引。
如果你能帮忙,我会给你买 6 包你最喜欢的饮料!
谢谢!