Using a custom image for a UITableViewCell's accessoryView and having it respond to UITableViewDelegate

后端 未结 10 2065
独厮守ぢ
独厮守ぢ 2020-11-27 09:35

I\'m using a custom drawn UITableViewCell, including the same for the cell\'s accessoryView. My setup for the accessoryView happens by the way of something like

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 09:43

    1. Define a macro for tags of buttons:

      #define AccessoryViewTagSinceValue 100000 // (AccessoryViewTagSinceValue * sections + rows) must be LE NSIntegerMax
      
    2. Create button and set the cell.accessoryView when creating a cell

      UIButton *accessoryButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
      accessoryButton.frame = CGRectMake(0, 0, 30, 30);
      [accessoryButton addTarget:self action:@selector(accessoryButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
      cell.accessoryView = accessoryButton;
      
    3. Set cell.accessoryView.tag by indexPath in UITableViewDataSource method -tableView:cellForRowAtIndexPath:

      cell.accessoryView.tag = indexPath.section * AccessoryViewTagSinceValue + indexPath.row;
      
    4. Event handler for buttons

      - (void) accessoryButtonTapped:(UIButton *)button {
          NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag % AccessoryViewTagSinceValue
                                                      inSection:button.tag / AccessoryViewTagSinceValue];
      
          [self.tableView.delegate tableView:self.tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
      }
      
    5. Implement the UITableViewDelegate method

      - (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
          // do sth.
      }
      

提交回复
热议问题