How do I set UITableViewCellSelectionStyle property to some custom color?

前端 未结 9 1749
栀梦
栀梦 2020-12-13 04:04

I am developing an iPhone application, in my table view I wanted custom color for Cell Selection Style, I read the UITableViewCell Class Reference but there are onl

9条回答
  •  遥遥无期
    2020-12-13 04:58

    I tried some of the above, and I actually prefer to create my own subclass of UITableViewCell and then override the touchesBegan/touchesCancelled/touchesEnded methods. To do this, ignore all the selectedBackgroundView and highlightedColor properties on the cell, and instead just set these colors manually whenever one of the above methods are called. For example, if you want to set the cell to have a green background with red text, try this (within your custom cell subclass):

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        //Set backgorund
        self.backgroundColor = [UIColor themeBlue];
    
        //Set text
        self.textLabel.textColor = [UIColor themeWhite];
    
        //Call super
        [super touchesBegan:touches withEvent:event];
    }
    

    Note that for this to work, you need to set:

    self.selectionStyle = UITableViewCellSelectionStyleNone;
    

    Otherwise, you'll first get the current selection style.

    EDIT: I suggest using the touchesCancelled method to revert back to the original cell colors, but just ignore the touchesEnded method.

提交回复
热议问题