简体   繁体   中英

UITableView: Show selected cell background only when in edit mode

When my tableView is not in edit mode, I don't want a user to be able to touch the cells and have them highlight. But, because I have set allowsSelectionDuringEditing to YES, users can select cells when in editing mode.

How do I only show the cell highlighted view or color ONLY when in editing mode?

Interesting scenario, luckily it's as simple as this:

// -tableView:shouldHighlightRowAtIndexPath: is called when a touch comes down on a row. 
// Returning NO to that message halts the selection process and does not cause the currently selected row to lose its selected look while the touch is down.
- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.isEditing;
}

As you can see from Apple's comment shouldHighlight is the first step in the selection process, so that is the place to halt it in the case of table being edited.

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  static NSString *CellIdentifier=@"Cell";
  UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if(cell==nil){
     //YOUR inits
  }

  if(self.editing){
    [cell setSelectionStyle:UITableViewCellEditingStyleNone];
  }else
    [cell setSelectionStyle:UITableViewCellEditingStyleBlue];

  return cell;

}

and

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  if(self.editing)return; //NO ACTION
}

I figured it out. Here is my method that sets tableView editing mode:

- (void)tableViewEdit {

    if (self.tableView.editing) {
        [self.editButton setTitle:NSLocalizedString(@"Edit", nil) forState:UIControlStateNormal];
        self.tableView.allowsSelection = NO;
    } else {
        [self.editButton setTitle:NSLocalizedString(@"Done", nil) forState:UIControlStateNormal];
        self.tableView.allowsSelection = YES;
    }
    [self.tableView setEditing:!self.tableView.editing animated:YES];

}//end

I also previously set self.tableView.allowsSelection to NO as a default, so it will only be YES after editing mode is entered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM