2013-04-28 4 views
43

Ho un menù in questo modo:Come cambiare il colore di UITableViewCell quando si seleziona?

Menu

Lo stato normale (non selezionato) per ogni cella è un'immagine, lo stato selezionato è anche un'immagine (che assomiglia a quello blu di default). Tuttavia, mi piacerebbe aggiungere una terza immagine aggiuntiva, in modo che quando l'utente seleziona una cella, passa brevemente a quel terzo colore prima di diventare blu (selezionato).

Questo è il mio codice:

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    [tableView setBackgroundColor:[UIColor clearColor]]; 

    NSString *cellIdentifier = @"MenuItemCell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier]; 
    } 

    UIImage *cellBackgroundNormal = [UIImage imageNamed:@"cell_menu_normal"]; 
    UIImage *cellBackgroundSelected = [UIImage imageNamed:@"cell_menu_selected"]; 
    UIImageView *cellBackgroundView = [[UIImageView alloc] initWithImage:cellBackgroundNormal]; 
    UIImageView *cellBackgroundSelectedView = [[UIImageView alloc] initWithImage:cellBackgroundSelected]; 
    cell.backgroundView = cellBackgroundView; 
    cell.selectedBackgroundView = cellBackgroundSelectedView; 

    [cell.textLabel setBackgroundColor:[UIColor clearColor]]; 
    [cell.textLabel setTextColor:[UIColor whiteColor]]; 
    [cell.textLabel setFont:[UIFont boldSystemFontOfSize:17.0]]; 
    cell.textLabel.text = [self.menuItems objectAtIndex:indexPath.row]; 

    return cell; 
} 

Come potete vedere, ho solo due stati, al momento. Non vedo come posso introdurre una sorta di cell.hoveredBackgroundView per la terza immagine. Se qualcuno può aiutarmi a implementarlo, lo apprezzerei davvero.

risposta

90

iOS 6.0 e versioni successive

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath { 
return YES; 
} 

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

- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath { 
    // Reset Colour. 
    CustomCell *cell = (CustomCell *)[tableView cellForRowAtIndexPath:indexPath]; 
    [self setCellColor:[UIColor colorWithWhite:0.961 alpha:1.000] ForCell:cell]; //normal color 

} 

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

personalizzato UITableViewCell

- (void)setSelected:(BOOL)selected animated:(BOOL)animated { 
    [super setSelected:selected animated:animated]; 

    UIView * selectedBackgroundView = [[UIView alloc] init]; 
    [selectedBackgroundView setBackgroundColor:[UIColor colorFromHexString:@"5E6073"]]; // set color here 
    [self setSelectedBackgroundView:selectedBackgroundView]; 
} 
+1

Grazie, è tutto! Ho anche dovuto implementare 'didUnhighlightRowAtIndexPath' per gestire le modifiche alle immagini quando una riga viene deselezionata. – swiftcode

+0

Potresti migliorare il codice per mostrare come cambiare il colore della cella per favore? :) – Lucien

+0

@Lucien Ho aggiornato il codice. Provalo – Ayush

-4

È possibile introdurre un timer per impostare il tempo desiderato (ad esempio 1/2 s se ho capito) tra i 2 diversi colori di sfondo? Ma si può già pensato a questo:/

+0

Non credo che funzionerebbe, perché voglio che lo stato in quello stato intermedio per tutto il tempo in cui l'utente tiene il dito premuto sulla voce di menu selezionata e cambia solo in blu al momento del rilascio. È come un pulsante, ad esempio, che ha il proprio stato evidenziato. – swiftcode

+1

Questi sembrano piuttosto hacky e non del tutto affidabili –

-1

Si potrebbe creare un costume UITableViewCell, in cui si aggiunge un UIButton con la dimensione della cella. Quindi puoi facilmente creare metodi personalizzati per gli eventi TouchDown (passaggio del mouse) e TouchUpInside di UIButton e impostare lo sfondo.

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

Prova questa in costume cellulo

- (void)awakeFromNib 
{ 
    UIView *selectedBackgroundView = [[UIView alloc] initWithFrame:self.bounds]; 
    selectedBackgroundView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; 
    selectedBackgroundView.backgroundColor = [UIColor colorWithRed:246.0/255.0 green:95.0/255.0 blue:22.0/255.0 alpha:1.0]; 
    self.selectedBackgroundView = selectedBackgroundView; 
} 
30

8 iOS.0 (e versioni successive) utilizzando Swift

Swift 2

override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool { 
    return true 
} 

override func tableView(tableView: UITableView, didHighlightRowAtIndexPath indexPath: NSIndexPath) { 
    var cell = tableView.cellForRowAtIndexPath(indexPath) 
    cell?.contentView.backgroundColor = UIColor.orangeColor() 
    cell?.backgroundColor = UIColor.orangeColor() 
} 

override func tableView(tableView: UITableView, didUnhighlightRowAtIndexPath indexPath: NSIndexPath) { 
    var cell = tableView.cellForRowAtIndexPath(indexPath) 
    cell?.contentView.backgroundColor = UIColor.blackColor() 
    cell?.backgroundColor = UIColor.blackColor() 
} 

Swift 3

override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { 
    return true 
} 

override func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) { 
    let cell = tableView.cellForRow(at: indexPath) 
    cell?.contentView.backgroundColor = UIColor.orange 
    cell?.backgroundColor = UIColor.orange 
} 

override func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) { 
    let cell = tableView.cellForRow(at: indexPath) 
    cell?.contentView.backgroundColor = UIColor.black 
    cell?.backgroundColor = UIColor.black 
} 

enter image description here

14

Più facile che risposta accettata:

Nel vostro UITableViewCell sottoclasse:

In awakeFromNib o init:

self.selectionStyle = UITableViewCellSelectionStyleNone;

Poi:

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated 
{ 
    [super setHighlighted:highlighted animated:animated]; 

    if (highlighted) { 
     self.backgroundColor = [UIColor yourHighlightColor]; 
    } 
    else { 
     self.backgroundColor = [UIColor yourNormalColor]; 
    } 
} 
6

Swift:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    tableView.deselectRowAtIndexPath(indexPath, animated: true) 
} 

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { 
    let selectionColor = UIView() as UIView 
    selectionColor.layer.borderWidth = 1 
    selectionColor.layer.borderColor = UIColor.blueColor().CGColor 
    selectionColor.backgroundColor = UIColor.blueColor() 
    cell.selectedBackgroundView = selectionColor 
} 

Swift 4:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
{ 
    tableView.deselectRow(at: indexPath, animated: true) 
} 

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) 
{ 
    let selectionColor = UIView() as UIView 
    selectionColor.layer.borderWidth = 1 
    selectionColor.layer.borderColor = UIColor.blue.cgColor 
    selectionColor.backgroundColor = UIColor.blue 
    cell.selectedBackgroundView = selectionColor 
} 
+0

grazie ha funzionato per me .. –

+1

Strettamente, questa è l'unica risposta corretta qui. – mxcl

+0

Ha funzionato anche per me, ho aggiunto una versione di Swift 4. –

32

È inoltre possibile utilizzare UIAppearance come questo:

UIView *selectionView = [UIView new]; 
selectionView.backgroundColor = [UIColor redColor]; 
[[UITableViewCell appearance] setSelectedBackgroundView:selectionView]; 

Ciò si applicherà a tutte le istanze di UITableViewCell o di qualsiasi delle sue sottoclassi che potreste avere. Assicurati che la proprietà selectionStyle della cella sia non impostata su UITableViewCellSelectionStyleNone.

+10

Grazie! Questo è, ** mani giù **, la risposta più elegante. La risposta accettata sembra il codice di un tempo. ** Ecco lo stesso codice in Swift: ** http://d.pr/n/14HUv –

+2

Tuttavia con questa soluzione, la selezione multipla agisce in modo molto strano. (è possibile evidenziare solo una riga) – Gannicus

+2

Questa operazione interrompe l'animazione deselezionata delle celle quando si torna a un controller di visualizzazione tabella precedente nella navigazione: La deselezione diventa immediata ed è impossibile stabilire quale riga è stata selezionata. –

3

Sulla base della risposta di Milan Cermak, è possibile utilizzare UIAppearance.

In Swift 1.1/2.0:

let selectionView = UIView() 
selectionView.backgroundColor = UIColor.redColor() 
UITableViewCell.appearance().selectedBackgroundView = selectionView 
2

Utilizzando Objective C, cambiare cella selezionata sfondo di colore diverso da quello di default. Non è necessario creare celle personalizzate.

Se si desidera solo cambiare il colore selezionato della cella, si può fare questo, tenere presente che per far funzionare tutto questo, nella Storyboard (o file XIB) è necessario selezionare un colore di sfondo selezionato diverso Nessuna. Basta aggiungere seguente codice nel UITableView metodo delegato: tableView cellForRowAtIndexPath:

UIView *bgColor = [[UIView alloc] init]; 

bgColor.backgroundColor = [UIColor yellowColor]; 

[cell setSelectedBackgroundView:bgColor]; 
0

Add seguente codice al metodo cellForRowAtIndexPath

var cell=tableView.dequeueReusableCellWithIdentifier("cell")! 
var viewBG=UIView(frame: CGRectMake(0,0,self.view.frame.size.width,50)) 
viewBG.backgroundColor=UIColor(colorLiteralRed: 71.0/255.0, green: 121.0/255.0, blue: 172.0/255.0, alpha: 1) 
cell.selectedBackgroundView=viewBG 
0

per SWIFT 3

self.tableView.reloadData() 
let selectedCell = tableView.cellForRow(at: indexPath) 
selectedCell?.contentView.backgroundColor = UIColor.red 
1

personalizzato UITableViewCell Swift 3.0

override func awakeFromNib() { 
     super.awakeFromNib() 

     let selectedBackgroundView = UIView(); 
     selectedBackgroundView.backgroundColor = UIColor.lightGray; 
     self.selectedBackgroundView = selectedBackgroundView; 
    } 
0

Finisco con il seguente codice.

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

    // UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[cellIdArray objectAtIndex:indexPath.row] forIndexPath:indexPath]; 

    // Configure the cell... 
    cell.backgroundView = 
    [[UIImageView alloc] init] ; 
    cell.selectedBackgroundView =[[UIImageView alloc] init]; 

    UIImage *rowBackground; 
    UIImage *selectionBackground; 


    rowBackground = [UIImage imageNamed:@"cellBackgroundDarkGrey.png"]; 
    selectionBackground = [UIImage imageNamed:@"selectedMenu.png"]; 

    ((UIImageView *)cell.backgroundView).image = rowBackground; 
    ((UIImageView *)cell.selectedBackgroundView).image = selectionBackground; 



    return cell; 
}