Qualcuno sa come cambiare il colore di sfondo di una cella usando UITableViewCell, per ogni cella selezionata? Ho creato questo UITableViewCell all’interno del codice per TableView.
La modifica della proprietà selectedBackgroundView è corretta e il modo più semplice. Io uso il seguente codice per cambiare il colore di selezione:
// set selection color UIView *myBackView = [[UIView alloc] initWithFrame:cell.frame]; myBackView.backgroundColor = [UIColor colorWithRed:1 green:1 blue:0.75 alpha:1]; cell.selectedBackgroundView = myBackView; [myBackView release];
Sono finalmente riuscito a far funzionare tutto in una vista tabella con lo stile impostato su Raggruppato.
Prima imposta la proprietà selectionStyle
di tutte le celle su UITableViewCellSelectionStyleNone
.
cell.selectionStyle = UITableViewCellSelectionStyleNone;
Quindi implementare quanto segue nella delegazione della vista tabella:
static NSColor *SelectedCellBGColor = ...; static NSColor *NotSelectedCellBGColor = ...; - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSIndexPath *currentSelectedIndexPath = [tableView indexPathForSelectedRow]; if (currentSelectedIndexPath != nil) { [[tableView cellForRowAtIndexPath:currentSelectedIndexPath] setBackgroundColor:NotSelectedCellBGColor]; } return indexPath; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [[tableView cellForRowAtIndexPath:indexPath] setBackgroundColor:SelectedCellBGColor]; } - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { if (cell.isSelected == YES) { [cell setBackgroundColor:SelectedCellBGColor]; } else { [cell setBackgroundColor:NotSelectedCellBGColor]; } }
// animate between regular and selected state - (void)setSelected:(BOOL)selected animated:(BOOL)animated { [super setSelected:selected animated:animated]; if (selected) { self.backgroundColor = [UIColor colorWithRed:234.0f/255 green:202.0f/255 blue:255.0f/255 alpha:1.0f]; } else { self.backgroundColor = [UIColor clearColor]; } }
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath]; cell.contentView.backgroundColor = [UIColor yellowColor]; }
Ho creato UIView e impostato la proprietà della cella selectedBackgroundView:
UIView *v = [[UIView alloc] init]; v.backgroundColor = [UIColor redColor]; cell.selectedBackgroundView = v;
Se parli di celle selezionate, la proprietà è -selectedBackgroundView
. Questo verrà mostrato quando l’utente seleziona la tua cella.
Dopo alcuni test questo rimuoverà il colore di sfondo quando deselezionato o la cella viene TAPpata una seconda volta quando la vista tabella è impostata su “Selezione multipla”. Funziona anche quando la vista tabella è impostata su “Raggruppato”.
extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let cell = tableView.cellForRow(at: indexPath) { cell.contentView.backgroundColor = UIColor.darkGray } } }
Nota: affinché funzioni come vedi sotto, la proprietà Selection della tua cella può essere impostata su qualsiasi cosa MA Nessuno.
Stile: normale , selezione: selezione singola
Stile: normale , selezione: selezione multipla
Stile: raggruppato , selezione: selezione multipla
Per una transizione dei colors più fluida, prova alcune animazioni:
extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let cell = tableView.cellForRow(at: indexPath) { UIView.animate(withDuration: 0.3, animations: { cell.contentView.backgroundColor = UIColor.darkGray }) } } }
Si può notare che l’icona e il colore del testo cambiano anche quando viene selezionata la cella. Ciò accade automaticamente quando si impostano le proprietà evidenziate UIImage e UILabel
UIImage
UILabel
Basta fornire un colore per la proprietà Evidenziata:
Ho avuto fortuna con quanto segue:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { bool isSelected = // enter your own code here if (isSelected) { [cell setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:0.75 alpha:1]]; [cell setAccessibilityTraits:UIAccessibilityTraitSelected]; } else { [cell setBackgroundColor:[UIColor clearColor]]; [cell setAccessibilityTraits:0]; } }
Ho un UITableViewCell altamente personalizzato. Quindi ho implementato la mia selezione di celle.
cell.selectionStyle = UITableViewCellSelectionStyleNone;
Ho creato un metodo nella class della mia cella:
- (void)highlightCell:(BOOL)highlight { if (highlight) { self.contentView.backgroundColor = RGB(0x355881); _bodyLabel.textColor = RGB(0xffffff); _fromLabel.textColor = RGB(0xffffff); _subjectLabel.textColor = RGB(0xffffff); _dateLabel.textColor = RGB(0xffffff); } else { self.contentView.backgroundColor = RGB(0xf7f7f7);; _bodyLabel.textColor = RGB(0xaaaaaa); _fromLabel.textColor = [UIColor blackColor]; _subjectLabel.textColor = [UIColor blackColor]; _dateLabel.textColor = RGB(0x496487); } }
Nella mia class UITableViewController in ViewWillAppear è stato aggiunto questo:
NSIndexPath *tableSelection = [self.tableView indexPathForSelectedRow]; SideSwipeTableViewCell *cell = (SideSwipeTableViewCell*)[self.tableView cellForRowAtIndexPath:tableSelection]; [cell highlightCell:NO];
In didSelectRow ha aggiunto questo:
SideSwipeTableViewCell *cell = (SideSwipeTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath]; [cell highlightCell:YES];
Per iOS7 + e se si utilizza Interface Builder, creare una sottoclass della cella e implementare:
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()) }
Ciò ha funzionato perfettamente con le chiamate raggruppate: implementa una sottoclass personalizzata di UITableViewCell
Questo rispetterà gli angoli e così …
- (void)setSelected:(BOOL)selected animated:(BOOL)animated { [super setSelected:selected animated:animated]; if(selected) [self setBackgroundColor:[UIColor colorWithRed:(245/255.0) green:(255/255.0) blue:(255/255.0) alpha:1]]; else [self setBackgroundColor:[UIColor whiteColor]]; }
Se desideri solo rimuovere il colore di sfondo grigio, procedi nel seguente modo:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [[tableView cellForRowAtIndexPath:indexPath] setSelectionStyle:UITableViewCellSelectionStyleNone]; }
Sono stato in grado di risolvere questo problema creando una sottoclass di UITableViewCell
e implementando il metodo setSelected: animated:
- (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]]; } }
Il trucco stava impostando il
cell.selectionStyle = UITableViewCellSelectionStyleDefault;
nel controller della vista di implementazione e quindi nella tabellaViewCell impostandolo come
[self setSelectionStyle:UITableViewCellSelectionStyleNone];
Spero che questo ti aiuti. 🙂
Lo stile predefinito è grigio e distrugge i colors della cella se è stata eseguita a livello di programmazione. Puoi farlo per evitarlo. (in Swift)
cell.selectionStyle = .None
In Swift
let v = UIView() v.backgroundColor = self.darkerColor(color) cell?.selectedBackgroundView = v; ... func darkerColor( color: UIColor) -> UIColor { var h = CGFloat(0) var s = CGFloat(0) var b = CGFloat(0) var a = CGFloat(0) let hueObtained = color.getHue(&h, saturation: &s, brightness: &b, alpha: &a) if hueObtained { return UIColor(hue: h, saturation: s, brightness: b * 0.75, alpha: a) } return color }
Consulta AdvancedTableViewCells
nel codice di esempio di Apple .
Ti consigliamo di utilizzare il modello di cella composito.
Crea un UITableViewCell personalizzato. All’interno della class personalizzata si sostituisce la funzione “setSelected” e si modifica il colore di sfondo contentView . Puoi anche annullare la funzione “setHighlighted”.
In Swift:
class myTableViewCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state // Add your color here self.contentView.backgroundColor = UIColor.whiteColor() } override func setHighlighted(highlighted: Bool, animated: Bool) { // Add your color here self.contentView.backgroundColor = UIColor.whiteColor() } }
Per me va bene
UIView *customColorView = [[UIView alloc] init]; customColorView.backgroundColor = [UIColor colorWithRed:180/255.0 green:138/255.0 blue:171/255.0 alpha:0.5]; cell.selectedBackgroundView = customColorView;
in Swift 3, convertito dalla risposta illumina.
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 } }
(tuttavia la vista cambia solo quando la selezione viene confermata rilasciando il dito)
Ecco un modo rapido per farlo direttamente in Interface Builder (all’interno di uno Storyboard). Trascina un semplice UIView nella parte superiore di UITableView come in Quindi collega la presa
selectedBackgroundView
BackgroundView alla tua vista. Puoi persino colbind prese multiple di celle a questa vista.
Per una soluzione che funziona (correttamente) con UIAppearance
per iOS 7 (e versioni successive?) Sottoclassi UITableViewCell
e usando il suo predefinito selectedBackgroundView
per impostare il colore, dai un’occhiata alla mia risposta a una domanda simile qui .
- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath]; cell.contentView.backgroundColor = [UIColor yellowColor]; } - (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath]; cell.contentView.backgroundColor = nil; }
Ho provato ognuna delle risposte di cui sopra, ma nessuna si adatta meglio per me,
poi ho esaminato uno dei metodi nativi forniti, e sta funzionando bene.
per prima cosa, imposta cellSelectionStyle su None e poi cerca questa soluzione.
func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? { let cell = tableView.cellForRow(at: indexPath); //cell which is getting deselected, make whatever changes that are required to make it back normal cell.backgroundColor = kNormalColor; return indexPath; } func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { let cell = tableView.cellForRow(at: indexPath); //cell which is getting selected, make whatever changes that are required to make it selected cell.backgroundColor = kSelectedColor; return indexPath; }
il vantaggio di questi metodi rispetto agli altri è:
override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) if selected { self.contentView.backgroundColor = .black } else { self.contentView.backgroundColor = .white } }