刷新表查看数据,然后取消选择单元格(Reload Table View Data and Desel

2019-09-16 18:02发布

我有一个表视图,其中我想从一个详细视图或新加入的细胞返回到它时,当用户创建一个项以取消选择任一先前选定的小区。

然而,由于添加有时新项目,该表是通过调用刷新reloadDataviewWillAppear: 。 这意味着没有一个细胞的视图显示时被选择时,即使我有self.clearsSelectionOnViewWillAppear = NO

通过选择和取消出现的表视图单元格(在viewDidAppear:取消选定动画的时机是对用户明显不同(自己尝试,它的速度较慢,不会感觉华而不实)。

我应该如何保存选择后连表视图被刷新? (请注意,根据不同的情况,我想了取消或者先前选定的单元格或新建的小区。),还是应该以某种方式被我重装不同在我的表中的数据?

Answer 1:

你可以保存NSIndexPath- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath方法和视图时重新加载取消选择该行。

这样做的另一种方式可能是通过传递NSIndexPath和当前UITableViewControllerUIViewController你创建和时UIViewController被弹出,取消选择特定行。

当创建一个新的项目,添加一个到indexPath的行元素取消选择权的行。

您也可以加载只有已更改的行:

[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                      withRowAnimation:UITableViewRowAnimationNone];

[self.tableView selectRowAtIndexPath:indexPath 
                            animated:NO
                      scrollPosition:UITableViewScrollPositionNone];

[self.tableView deselectRowAtIndexPath:indexPath animated:YES];


Answer 2:

更先进的解决方案:

  • 它与[self.tableView reloadData]
  • 当选择行重载之后缺少它不会崩溃。

从示例代码部分MyViewController.m

@interface MyViewController ()
{
    MyViewModel* _viewModel;
    NSString* _selectedItemUniqueId;
}

@property (nonatomic, weak) IBOutlet UITableView* tableView;

@end

@implementation MyViewController

#pragma mark - UIViewController methods

- (void)viewDidLoad
{
    [super viewDidLoad];
    _selectedItemUniqueId = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    // Get data for selected row.
    Item* item = _viewModel.data.sections[indexPath.section].items[indexPath.row];

    // Remember selection that we could restore it when viewWillAppear calls [self.tableView reloadData].
    _selectedItemUniqueId = item.uniqueId;

    // Go to details view.
}

- (void)tableView:(UITableView*)tableView willDisplayCell:(nonnull UITableViewCell *)cell forRowAtIndexPath:(nonnull NSIndexPath *)indexPath {

    // Get data for row.
    Item* item = _viewModel.data.sections[indexPath.section].items[indexPath.row];

    // Bring back selection which is destroyed by [self.tableView reloadData] in viewWillAppear.
    BOOL selected = _selectedItemUniqueId && [item.uniqueId isEqualToString:_selectedItemUniqueId];
    if (selected) {
        _selectedItemUniqueId = nil;
        [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
}

@end


文章来源: Reload Table View Data and Deselect Cell