web-dev-qa-db-fra.com

Comment définir la propriété UITableViewCellSelectionStyle sur une couleur personnalisée?

Je développe une application iPhone. Dans mon affichage de tableau, je voulais une couleur personnalisée pour le style de sélection de cellule, je lis le UITableViewCell Class Reference mais il n'y a que trois constantes définies pour le style de sélection (Bleu, Gris, Aucun). J'ai vu une application qui utilisait une couleur différente de celle définie dans la référence.

Comment pouvons-nous utiliser une couleur autre que celles définies dans la référence?

Merci d'avance.

35
Amit Vaghela

Le meilleur moyen de définir la sélection consiste à définir selectedBackgroundView sur la cellule lors de sa construction.

c'est à dire.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
        cell.selectedBackgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"SelectedCellBackground.png"]] autorelease];
    }

    // configure the cell
}

L'image utilisée doit avoir un dégradé de Nice (comme la sélection par défaut). Si vous souhaitez simplement une couleur unie, vous pouvez utiliser UIView au lieu de UIImageView et définir le backgroundColor sur la couleur souhaitée.

Cet arrière-plan est ensuite automatiquement appliqué lorsque la ligne est sélectionnée.

64
Matt Gallagher

Définir selectedBackgroundView semble n'avoir aucun effet lorsque cell.selectionStyle est défini sur UITableViewCellSelectionStyleNone. Lorsque je ne définis pas le style, il utilise simplement le gris par défaut. 

L'utilisation de la première suggestion qui insère la variable UIView personnalisée dans la cellule manipule la cellule, mais ne s'affiche pas lorsque la cellule est touchée, uniquement une fois l'action sélectionnée terminée, ce qui est trop tard car je passe à une nouvelle vue. Comment obtenir l'affichage de la vue sélectionnée dans la cellule avant le début de l'opération sélectionnée?

24
Paul

Si vous avez sous-classé une UITableViewCell, vous pouvez personnaliser les différents éléments de la cellule en remplaçant les éléments suivants:

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
    if(highlighted) {
        self.backgroundColor = [UIColor redColor];
    } else {
        self.backgroundColor = [UIColor clearColor];
    }

    [super setHighlighted:highlighted animated:animated];
}

EDIT pour iOS7: Comme le dit Sasho, vous avez également besoin 

cell.selectionStyle = UITableViewCellSelectionStyleNone
12
Willster

J'ai essayé certaines des solutions ci-dessus et je préfère créer ma propre sous-classe UITableViewCell, puis remplacer les méthodes touchesBegan/touchesCancelled/touchesEnded . Pour ce faire, ignorez toutes les propriétés selectedBackgroundView et highlightColor de la cellule et définissez simplement ces couleurs manuellement chaque fois que l'une des méthodes ci-dessus est appelée. Par exemple, si vous souhaitez que la cellule ait un arrière-plan vert avec du texte rouge, essayez ceci (dans votre sous-classe de cellule personnalisée):

- (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];
}

Notez que pour que cela fonctionne, vous devez définir:

self.selectionStyle = UITableViewCellSelectionStyleNone;

Sinon, vous obtiendrez d'abord le style de sélection actuel.

EDIT: Je suggère d'utiliser la méthode touchesCancelled pour rétablir les couleurs de cellule d'origine, mais ignorer simplement la méthode touchesEnded.

7
Charles Marsh

Substituez didSelectRowAtIndexPath: et dessinez une vue UIV d'une couleur de votre choix et insérez-la derrière le UILabel à l'intérieur de la cellule. Je le ferais quelque chose comme ça:

UIView* selectedView; //inside your header

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

  UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
  selectedView = [[UIView alloc] initWithFrame:[cell frame]];
  selectedView.backgroundColor = [UIColor greenColor]; //whatever

  [cell insertSubview:selectedView atIndex:0]; //Tweak this as necessary
  [selectedView release]; //clean up

}

Vous pouvez choisir d’animer cette vue lorsqu’elle est désélectionnée et répondra à vos exigences.

2
Jeffrey Forbes

Sublcass UITableViewCell et remplacer setHighlighted:animated:

Vous pouvez définir une couleur de couleur de sélection personnalisée en définissant backgroundColor (voir la réponse de WIllster):

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
    if(highlighted) {
        self.backgroundColor = [UIColor redColor];
    } else {
        self.backgroundColor = [UIColor clearColor];
    }

    [super setHighlighted:highlighted animated:animated];
}

Vous pouvez définir une image d’arrière-plan personnalisée en définissant la propriété backgroundView:

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
    if( highlighted == YES )
        self.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"seasonal_list_event_bar_default.png"]];
    else
        self.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"seasonal_list_event_bar_active.png"]];


    [super setHighlighted:highlighted animated:animated];
}
1
bentford

Pour ajouter une couleur personnalisée, utilisez le code ci-dessous. Et pour le rendre transparent, utilisez alpha: 0.0

cell.selectedBackgroundView = UIView(frame: CGRect.zero)
cell.selectedBackgroundView?.backgroundColor = UIColor(red:0.27, green:0.71, blue:0.73, alpha:1.0)

Si vous utilisez une couleur personnalisée et souhaitez lui donner un aspect arrondi, utilisez:

cell.layer.cornerRadius = 8

En outre, utilisez-le pour une meilleure animation et ressentez

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    tableView.deselectRow(at: indexPath, animated: true)
}
0
Prateekro
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {  
// Set Highlighted Color  
if (highlighted) {  
self.backgroundColor = [UIColor colorWithRed:234.0f/255 green:202.0f/255 blue:255.0f/255 alpha:1.0f];
    } else {  
        self.backgroundColor = [UIColor clearColor];  
  }   
}
0
PK86
- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    // Add your Colour.
    SocialTableViewCell *cell = (SocialTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    [self setCellColor:Ripple_Colour ForCell:cell];  //highlight colour
}

- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    // Reset Colour.
    SocialTableViewCell *cell = (SocialTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    [self setCellColor:Ripple_Colour ForCell:cell]; //normal color

}

- (void)setCellColor:(UIColor *)color ForCell:(UITableViewCell *)cell {
    cell.contentView.backgroundColor = color;
    cell.backgroundColor = color;
}
0
Ishwar Hingu