Changing background color of selected cell?

后端 未结 30 2960
太阳男子
太阳男子 2020-11-29 00:22

Does anyone know how to change the background color of a cell using UITableViewCell, for each selected cell? I created this UITableViewCell inside the code for TableView.

30条回答
  •  半阙折子戏
    2020-11-29 01:00

    I was able to solve this problem by creating a subclass of UITableViewCell and implementing the setSelected:animated: method

    - (void)setSelected:(BOOL)selected animated:(BOOL)animated {
        [super setSelected:selected animated:animated];
    
        // Configure the view for the selected state
        if(selected) {
            [self setSelectionStyle:UITableViewCellSelectionStyleNone];
            [self setBackgroundColor:[UIColor greenColor]];
        } else {
            [self setBackgroundColor:[UIColor whiteColor]];
        }
    }
    

    The trick was setting the

    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    

    in the implementing view controller and then in the tableViewCell setting it as

    [self setSelectionStyle:UITableViewCellSelectionStyleNone];
    

    Hope this helps. :)

提交回复
热议问题