重新排序UITableView行时,详细信息视图不会更新

时间:2014-09-08 15:39:51

标签: ios uitableview didselectrowatindexpath nsindexpath

我有一个推送到Detail ViewController的UITableView。在我的tableview中,我的行是可拖动/可重新排列的。但是,切换行时,选择行时路径保持不变,并显示详细信息视图。示例:TableView Re-order Pic

如果我要将“Milk”行切换为“Gym”行,然后选择“Gym”,则详细视图仍会返回奶行的详细信息。

如何解决这个问题,以便行的路径可以正常切换?

.m:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self->newArray count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    NSDictionary *theFood = [values objectAtIndex:indexPath.row];
    cell.textLabel.text = [theFood valueForKey:@"name"];
    cell.detailTextLabel.text = [theFood valueForKey:@"price"];

    return cell;
}



- (IBAction) EditTable:(id)sender
{
    if(self.editing)
    {
        [super setEditing:NO animated:NO];
        [_myTableView setEditing:NO animated:NO];
       // [_myTableView reloadData];
        [self.navigationItem.leftBarButtonItem setTitle:@"Edit"];
        [self.navigationItem.leftBarButtonItem setStyle:UIBarButtonItemStylePlain];
    }
    else
    {
        [super setEditing:YES animated:YES];
        [_myTableView setEditing:YES animated:YES];
       // [_myTableView reloadData];
        [self.navigationItem.leftBarButtonItem setTitle:@"Done"];
        [self.navigationItem.leftBarButtonItem setStyle:UIBarButtonItemStyleDone];

    }
}


- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
        if( fromIndexPath == toIndexPath ) {
            return;
        }

    NSDictionary *moveFood = [self->newArray objectAtIndex:fromIndexPath.row];
    [self->newArray removeObjectAtIndex:fromIndexPath.row];
    [self->newArray insertObject:moveFood atIndex:toIndexPath.row];



}



- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"detailSegue"]) {
        NSIndexPath *indexPath = [self.myTableView indexPathForSelectedRow];
        DetailViewController *detailVC = segue.destinationViewController;
        detailVC.detailFood = [values objectAtIndex:indexPath.row];

    }
}

2 个答案:

答案 0 :(得分:0)

切换行时,还应更新数据源。否则,当调用tableView的didSelect方法时,它将访问数据源数组中的错误对象。

所以在–tableView:moveRowAtIndexPath:toIndexPath:中切换已切换对象的位置。

答案 1 :(得分:0)

特别感谢@HotLicks帮助我!

问题是我在tableView:moveRowAtIndexPath:toIndexPath:方法更新后没有将详细信息视图的数据源从值NSArray更改为newArray NSMutableArray!