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

后端 未结 10 2039
独厮守ぢ
独厮守ぢ 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:56

    I found this website to be very helpful: custom accessory view for your uitableview in iphone

    In short, use this in cellForRowAtIndexPath::

    UIImage *image = (checked) ? [UIImage imageNamed:@"checked.png"] : [UIImage imageNamed:@"unchecked.png"];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
    button.frame = frame;
    [button setBackgroundImage:image forState:UIControlStateNormal];
    
    [button addTarget:self action:@selector(checkButtonTapped:event:)  forControlEvents:UIControlEventTouchUpInside];
    button.backgroundColor = [UIColor clearColor];
    cell.accessoryView = button;
    

    then, implement this method:

    - (void)checkButtonTapped:(id)sender event:(id)event
    {
        NSSet *touches = [event allTouches];
        UITouch *touch = [touches anyObject];
        CGPoint currentTouchPosition = [touch locationInView:self.tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
    
        if (indexPath != nil)
        {
            [self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
        }
    }
    

提交回复
热议问题