Changing background color of selected cell?

后端 未结 30 2687
太阳男子
太阳男子 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 00:57

    For iOS7+ and if you are using Interface Builder then subclass your cell and implement:

    Objective-C

    - (void)awakeFromNib {
        [super awakeFromNib];
        // Default Select background
        UIView *v = [[UIView alloc] init];
        v.backgroundColor = [UIColor redColor];
        self.selectedBackgroundView = v;
    }
    

    Swift 2.2

    override func awakeFromNib() {
        super.awakeFromNib()
        // Default Select background
        self.selectedBackgroundView = { view in
            view.backgroundColor = .redColor()
            return view
        }(UIView())
    }
    
    0 讨论(0)
  • 2020-11-29 00:58

    The default style is gray and it destroys the colors of the cell if it was done programmatically. You can do this to avoid that. (in Swift)
    cell.selectionStyle = .None

    0 讨论(0)
  • 2020-11-29 00:59

    Check out AdvancedTableViewCells in Apple's sample code.

    You'll want to use the composite cell pattern.

    0 讨论(0)
  • 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. :)

    0 讨论(0)
  • 2020-11-29 01:01

    If you just want to remove the grey background color do this :

    -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
         [[tableView cellForRowAtIndexPath:indexPath] setSelectionStyle:UITableViewCellSelectionStyleNone];
    }     
    
    0 讨论(0)
  • 2020-11-29 01:04

    in Swift 3, converted from illuminates answer.

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        if(selected) {
            self.selectionStyle = .none
            self.backgroundColor = UIColor.green
        } else {
            self.backgroundColor = UIColor.blue
        }
    }
    

    (however the view only changes once the selection is confirmed by releasing your finger)

    0 讨论(0)
提交回复
热议问题