How to change color of UITableViewCell when selecting?

前端 未结 14 2543
予麋鹿
予麋鹿 2020-12-04 10:59

I have a menu like so:

\"Menu\"

The normal (unselected) state for each cell is an image, the selected s

14条回答
  •  广开言路
    2020-12-04 11:37

    You could create a custom UITableViewCell, in which you add a UIButton with the size of the cell. Then you can easily make custom methods for the UIButton's TouchDown (hover) and TouchUpInside events, and set the background.

    - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
    {
        self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
        if (self) {
            cellButton = [[UIButton alloc] initWithFrame:self.contentView.frame];
            UIImage *cellBackgroundNormal = [UIImage imageNamed:@"cell_menu_normal"];
            UIImageView *cellBackgroundView = [[UIImageView alloc] initWithImage:cellBackgroundNormal];
            self.backgroundView = cellBackgroundView;
    
            [cellButton addTarget:self action:@selector(hoverCell) forControlEvents:UIControlEventTouchDown];
            [cellButton addTarget:self action:@selector(tapCell) forControlEvents:UIControlEventTouchUpInside];
        }
        return self;
    }
    
    - (void)hoverCell
    {
        UIImage *cellBackgroundHover = [UIImage imageNamed:@"cell_menu_third_image"];
        UIImageView *cellBackgroundHoverView = [[UIImageView alloc] initWithImage:cellBackgroundHover];
        self.backgroundView = cellBackgroundHoverView;
    }
    
    - (void)tapCell
    {
        UIImage *cellBackgroundSelected = [UIImage imageNamed:@"cell_menu_selected"];
        UIImageView *cellBackgroundSelectedView = [[UIImageView alloc] initWithImage:cellBackgroundSelected];
        self.backgroundView = cellBackgroundSelectedView;
    }
    

提交回复
热议问题