iosobjective-cuitableview

Use custom image to replace the check mark while tableview is being multiple selected


I tried to replace the check mark with a custom image. I used the method as below:

-(void)layoutSubviews
{
    [super layoutSubviews];
    for (UIControl *control in self.subviews){
        if ([control isMemberOfClass:NSClassFromString(@"UITableViewCellEditControl")]){
            for (UIView *v in control.subviews)
            {
                if ([v isKindOfClass: [UIImageView class]]) {
                    UIImageView *img=(UIImageView *)v;
                    if (self.selected) {
                        img.image= [UIImage createImageWithColor:[UIColor redColor]];
                    }else
                    {
                        img.image= [UIImage createImageWithColor:[UIColor yellowColor]];
                    }
                }
            }
        }
    }
}

It does work fine even though there's still a problem. There are no UIControl in self.subviews at the beginning.

enter image description here

As the picture showed. the check marks did not being replaced by the yellow image until I click on them.


Solution

  • you should call -setImageForCheckMark both in -layoutSubviews and -didTransitionToState. -didTransitionToState for the changing of cell state,-layoutSubviews for the changing of your click state

    -(void)layoutSubviews
    {
        // well ,while you change your cells' state into EditState ,-layoutSubviews will be invoked.
        // but the _imageView of control always be nil at end of layoutSubviews
        // I've try KVO to observe this _imageView ,but obviously it's not an attribute
        // Thankfully, UITableViewCell provide us with -willTransitionToState/-didTransitionToState
        [super layoutSubviews];
        [self setImageForCheckMark];
    }
    
    
    - (void)didTransitionToState:(UITableViewCellStateMask)state{
        // you should override it by your subclass ,when this method get called
        // all details of cell will be completed
        if (UITableViewCellStateShowingEditControlMask) {
            [self setImageForCheckMark];
        }
    }
    
    - (void)setImageForCheckMark{
        for (UIControl *control in self.subviews){
            if ([control isMemberOfClass:NSClassFromString(@"UITableViewCellEditControl")]){
                UIImageView *image = [control valueForKey:@"_imageView"];
                imageView.image = [UIImage createImageWithColor:self.selected?[UIColor yellowColor]:[UIColor greenColor]];
                break;
            }
        }
    }