Set UITableViewCell selected to YES in willDisplayCell: and the cell can't be deselected anymore

leb*_*aft 3 objective-c uitableview ios

I want to pre-select some rows in a multiple selection UITableView.

I do this in tableView:willDisplayCell:forRowAtIndexPath: by simply setting [cell setSelected:YES animated:NO];.

However, for some reason this disables deselection for these rows. The embedded controls still work, and so do detail disclosure buttons.

I have uploaded a sample project here: https://github.com/leberwurstsaft/TableViewIssue where you can check out the behavior (in Viewcontroller.m lines 49-51).

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cell setSelected:NO animated:NO]; //   -->   setSelected:YES and the cells can't be deselected anymore...
}
Run Code Online (Sandbox Code Playgroud)

什么似乎是问题?

Dre*_*w C 9

除了将单元格设置为选中之外,还需要通知tableView已选择单元格.添加-tableView:selectRowAtIndexPath:animated:scrollPosition:对您的willDisplayCell:方法的调用:您将能够正常取消选择它.

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (/*should be selected */) {
        [cell setSelected:YES animated:NO]; 
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    }
}
Run Code Online (Sandbox Code Playgroud)

这类似于@Ivan Loya的解决方案,但可以使用您已经使用的相同方法完成.务必使用UITableViewScrollPositionNone以避免奇怪的滚动行为.


Iva*_*oya 5

尝试这个在视图中确实出现,为我工作

- (void)viewDidAppear:(BOOL)animated {
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
    [_tableView selectRowAtIndexPath:indexPath animated:YES  scrollPosition:UITableViewScrollPositionBottom];
}
Run Code Online (Sandbox Code Playgroud)

在viewController.h中添加并链接到表视图

@property (weak, nonatomic) IBOutlet UITableView *tableView;
Run Code Online (Sandbox Code Playgroud)

并在willDisplayCell函数中注释该行