Ich habe ein benutzerdefiniertes UITableViewCell
erstellt. In der Tabellenansicht werden die Daten gut angezeigt. Wenn der Benutzer die Zelle der Tabellenansicht berührt, möchte ich eine andere Hintergrundfarbe als die Standardwerte [blaue Farbe] für die Hervorhebung der Zellenauswahl anzeigen. Ich benutze diesen Code, aber nichts passiert:
cell.selectedBackgroundView.backgroundColor=[UIColor blackColor];
Ich denke, Sie waren auf dem richtigen Weg, aber gemäß der Klassendefinition für selectedBackgroundView
:
Der Standardwert ist null für Zellen in Tabellen im einfachen Stil (UITableViewStylePlain) und nicht null für Abschnittsgruppentabellen (UITableViewStyleGrouped).
Wenn Sie eine einfache Tabelle verwenden, müssen Sie daher ein neues UIView
mit der gewünschten Hintergrundfarbe zuweisen-init und dann selectedBackgroundView
zuweisen.
Alternativ können Sie Folgendes verwenden:
cell.selectionStyle = UITableViewCellSelectionStyleGray;
wenn Sie nur einen grauen Hintergrund wollten, wenn die Zelle ausgewählt ist. Hoffe das hilft.
Keine benutzerdefinierten Zellen erforderlich. Wenn Sie nur die ausgewählte Farbe der Zelle ändern möchten, können Sie dies tun:
Ziel-C:
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];
Swift:
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.redColor()
cell.selectedBackgroundView = bgColorView
Swift 3:
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.red
cell.selectedBackgroundView = bgColorView
Swift 4.x:
let bgColorView = UIView()
bgColorView.backgroundColor = .red
cell.selectedBackgroundView = bgColorView
Bearbeiten: Aktualisiert für ARC
Bearbeiten: Fügt hinzu Swift 3
Wenn Sie eine gruppierte Tabelle mit nur einer Zelle pro Abschnitt haben, fügen Sie einfach diese zusätzliche Zeile zum Code hinzu: bgColorView.layer.cornerRadius = 10;
UIView *bgColorView = [[UIView alloc] init];
[bgColorView setBackgroundColor:[UIColor redColor]];
bgColorView.layer.cornerRadius = 10;
[cell setSelectedBackgroundView:bgColorView];
[bgColorView release];
Vergiss nicht, QuartzCore zu importieren.
Swift 3: Bei mir hat es funktioniert, als Sie es in das cellForRowAtIndexPath:
Methode
let view = UIView()
view.backgroundColor = UIColor.red
cell.selectedBackgroundView = view
Das Folgende funktioniert für mich in iOS 8.
Ich muss den Auswahlstil auf UITableViewCellSelectionStyleDefault
setzen, damit die benutzerdefinierte Hintergrundfarbe funktioniert. Bei allen anderen Stilen wird die benutzerdefinierte Hintergrundfarbe ignoriert. Das Verhalten scheint sich zu ändern, da bei vorherigen Antworten stattdessen kein Stil festgelegt werden muss.
Der vollständige Code für die Zelle lautet wie folgt:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"MyCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// This is how you change the background color
cell.selectionStyle = UITableViewCellSelectionStyleDefault;
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];
return cell;
}
Erstellen Sie eine benutzerdefinierte Zelle für Ihre Tabellenzelle, und geben Sie in der benutzerdefinierten Zellenklasse den folgenden Code ein, damit dies funktioniert. Sie müssen das gewünschte Farbbild in selectionBackground
UIImage platzieren.
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
UIImage *selectionBackground = [UIImage imageNamed:@"yellow_bar.png"];
UIImageView *iview=[[UIImageView alloc] initWithImage:selectionBackground];
self.selectedBackgroundView=iview;
}
extension UITableViewCell {
var selectionColor: UIColor {
set {
let view = UIView()
view.backgroundColor = newValue
self.selectedBackgroundView = view
}
get {
return self.selectedBackgroundView?.backgroundColor ?? UIColor.clear
}
}
}
cell.selectionColor = UIColor.FormaCar.blue
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
UIView *view = [[UIView alloc] init];
[view setBackgroundColor:[UIColor redColor]];
[cell setSelectedBackgroundView:view];
}
Wir müssen die ausgewählte Hintergrundansicht in dieser Methode einstellen.
In Swift 4 können Sie auch die Hintergrundfarbe Ihrer Tabellenzelle global festlegen (entnommen aus hier ):
let backgroundColorView = UIView()
backgroundColorView.backgroundColor = UIColor.red
UITableViewCell.appearance().selectedBackgroundView = backgroundColorView
Wenn Sie Ihrer Zelle eine benutzerdefinierte, hervorgehobene Farbe hinzufügen möchten (und Ihre Zelle Schaltflächen, Beschriftungen, Bilder usw. enthält), habe ich die folgenden Schritte ausgeführt:
Zum Beispiel, wenn Sie eine ausgewählte gelbe Farbe wünschen:
1) Erstellen Sie eine Ansicht, die für alle Zellen mit einer Deckkraft von 20% (mit gelber Farbe) geeignet ist, beispielsweise backgroundselectedView
2) Schreiben Sie in den Zellencontroller Folgendes:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
self.backgroundselectedView.alpha=1;
[super touchesBegan:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
self.backgroundselectedView.alpha=0;
[super touchesEnded:touches withEvent:event];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
self.backgroundSelectedImage.alpha=0;
[super touchesCancelled:touches withEvent:event];
}
Wenn Sie eine benutzerdefinierte TableViewCell verwenden, können Sie auch awakeFromNib
überschreiben:
override func awakeFromNib() {
super.awakeFromNib()
// Set background color
let view = UIView()
view.backgroundColor = UIColor.redColor()
selectedBackgroundView = view
}
Ein weiterer Tipp für Christian, wie er den Hintergrund mit abgerundeten Ecken für eine gruppierte Tabelle anzeigen kann.
Wenn ich cornerRadius = 10
Für eine Zelle verwende, wird der abgerundete Auswahlhintergrund für vier Ecken angezeigt. Dies ist nicht dasselbe mit der Standardbenutzeroberfläche der Tabellenansicht.
Also denke ich über einen einfachen Weg nach, es mit cornerRadius zu lösen. Wie Sie aus den folgenden Codes ersehen können, überprüfen Sie die Position der Zelle (oben, unten, in der Mitte oder oben) und fügen Sie eine weitere Unterebene hinzu, um die obere Ecke oder die untere Ecke auszublenden. Dies zeigt genau dasselbe Aussehen mit dem Auswahlhintergrund der Standardtabellenansicht.
Ich habe diesen Code mit dem iPad splitterview
getestet. Sie können die Frame-Position von patchLayer nach Bedarf ändern.
Bitte lassen Sie mich wissen, ob es einen einfacheren Weg gibt, das gleiche Ergebnis zu erzielen.
if (tableView.style == UITableViewStyleGrouped)
{
if (indexPath.row == 0)
{
cellPosition = CellGroupPositionAtTop;
}
else
{
cellPosition = CellGroupPositionAtMiddle;
}
NSInteger numberOfRows = [tableView numberOfRowsInSection:indexPath.section];
if (indexPath.row == numberOfRows - 1)
{
if (cellPosition == CellGroupPositionAtTop)
{
cellPosition = CellGroupPositionAtTopAndBottom;
}
else
{
cellPosition = CellGroupPositionAtBottom;
}
}
if (cellPosition != CellGroupPositionAtMiddle)
{
bgColorView.layer.cornerRadius = 10;
CALayer *patchLayer;
if (cellPosition == CellGroupPositionAtTop)
{
patchLayer = [CALayer layer];
patchLayer.frame = CGRectMake(0, 10, 302, 35);
patchLayer.backgroundColor = YOUR_BACKGROUND_COLOR;
[bgColorView.layer addSublayer:patchLayer];
}
else if (cellPosition == CellGroupPositionAtBottom)
{
patchLayer = [CALayer layer];
patchLayer.frame = CGRectMake(0, 0, 302, 35);
patchLayer.backgroundColor = YOUR_BACKGROUND_COLOR;
[bgColorView.layer addSublayer:patchLayer];
}
}
}
Gemäß der benutzerdefinierten Farbe für eine ausgewählte Zelle in UITableView
, eine großartige Lösung gemäß Maciej Swics Antwort
Um das noch zu ergänzen, deklarieren Sie Swic's answer in der Zellenkonfiguration normalerweise unter:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
Für einen zusätzlichen Effekt können Sie anstelle der Systemfarben RGB-Werte für ein benutzerdefiniertes Farblayout verwenden. In meinem Code habe ich Folgendes erreicht:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
}
static NSString *CellIdentifier = @"YourCustomCellName";
MakanTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
if (cell == nil) {
cell = [[[NSBundle mainBundle]loadNibNamed:@"YourCustomCellClassName" owner:self options:nil]objectAtIndex:0];
}
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor colorWithRed:255.0/256.0 green:239.0/256.0 blue:49.0/256.0 alpha:1];
bgColorView.layer.cornerRadius = 7;
bgColorView.layer.masksToBounds = YES;
[cell setSelectedBackgroundView:bgColorView];
return cell;
}
Lassen Sie mich wissen, ob das auch für Sie funktioniert. Sie können mit der Zahl cornerRadius
für die Effekte an den Ecken der ausgewählten Zelle herumspielen.
Ich habe einen etwas anderen Ansatz als alle anderen, der die Auswahl bei Berührung widerspiegelt und nicht erst nach der Auswahl. Ich habe eine untergeordnete UITableViewCell. Alles, was Sie tun müssen, ist, die Hintergrundfarbe in den Berührungsereignissen festzulegen, wodurch die Auswahl bei Berührung simuliert wird, und dann die Hintergrundfarbe in der Funktion setSelected festzulegen. Wenn Sie die Hintergrundfarbe in der Funktion selSelected festlegen, können Sie die Auswahl der Zelle aufheben. Stellen Sie sicher, dass das Berührungsereignis an den Super übergeben wird, sonst verhält sich die Zelle nicht so, als wäre sie ausgewählt.
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.backgroundColor = UIColor(white: 0.0, alpha: 0.1)
super.touchesBegan(touches, withEvent: event)
}
override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
self.backgroundColor = UIColor.clearColor()
super.touchesCancelled(touches, withEvent: event)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
self.backgroundColor = selected ? UIColor(white: 0.0, alpha: 0.1) : UIColor.clearColor()
}
Ich möchte darauf hinweisen, dass der XIB-Editor die folgenden Standardoptionen bietet:
Abschnitt: blau/grau/keine
(Die rechte Spalte mit Optionen, 4. Registerkarte, erste Gruppe "Tabellensichtzelle", 4. Untergruppe, der 1. von 3 Einträgen lautet "Auswahl")
Möglicherweise können Sie das erreichen, was Sie möchten, indem Sie die richtige Standardoption auswählen.
Das Überschreiben von UITableViewCell
funktioniert auch mit setSelected
.
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Set background color
let view = UIView()
view.backgroundColor = UIColor.redColor()
selectedBackgroundView = view
}
für Swift 3.0:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
cell.contentView.backgroundColor = UIColor.red
}
Fügen Sie folgende Zeilen in Ihre Tabellenzelle ein
let bgColorView = UIView()
bgColorView.backgroundColor = .red
self.selectedBackgroundView = bgColorView
Zum Schluss sollte es so sein wie unten
override func setSelected(_ selected: Bool, animated: Bool)
{
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
let bgColorView = UIView()
bgColorView.backgroundColor = .red
self.selectedBackgroundView = bgColorView
}
So fügen Sie den Hintergrund für alle Zellen hinzu (unter Verwendung von Maciejs Antwort):
for (int section = 0; section < [self.tableView numberOfSections]; section++) {
for (int row = 0; row < [self.tableView numberOfRowsInSection:section]; row++) {
NSIndexPath* cellPath = [NSIndexPath indexPathForRow:row inSection:section];
UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:cellPath];
//stuff to do with each cell
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];
}
}
für diejenigen, die nur den standardmäßig ausgewählten grauen Hintergrund entfernen möchten, fügen Sie diese Codezeile in Ihre cellForRowAtIndexPath-Funktion ein:
yourCell.selectionStyle = .None
Swift 4.x
Um die Hintergrundfarbe der Auswahl in anyColour zu ändern, verwenden Sie Swift Extension
Erstellen Sie die UITableView Cell-Erweiterung wie folgt
extension UITableViewCell{
func removeCellSelectionColour(){
let clearView = UIView()
clearView.backgroundColor = UIColor.clear
UITableViewCell.appearance().selectedBackgroundView = clearView
}
}
Rufen Sie dann removeCellSelectionColour () mit der Zelleninstanz auf.
Im Falle einer benutzerdefinierten Zellklasse. Einfach überschreiben:
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
if (selected) {
[self setBackgroundColor: CELL_SELECTED_BG_COLOR];
[self.contentView setBackgroundColor: CELL_SELECTED_BG_COLOR];
}else{
[self setBackgroundColor: [UIColor clearColor]];
[self.contentView setBackgroundColor: [UIColor clearColor]];
}
}
Hier sind die wichtigen Teile des Codes, die für eine gruppierte Tabelle benötigt werden. Wenn eine der Zellen in einem Abschnitt ausgewählt wird, ändert sich die Farbe der ersten Zeile. Ohne die anfängliche Einstellung von cellselectionstyle auf none gibt es ein unangenehmes doppeltes Neuladen, wenn der Benutzer auf row0 klickt und die Zelle in bgColorView wechselt. Anschließend wird bgColorView ausgeblendet und erneut geladen. Viel Glück und lass es mich wissen, wenn es einen einfacheren Weg gibt.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if ([indexPath row] == 0)
{
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIView *bgColorView = [[UIView alloc] init];
bgColorView.layer.cornerRadius = 7;
bgColorView.layer.masksToBounds = YES;
[bgColorView setBackgroundColor:[UIColor colorWithRed:.85 green:0 blue:0 alpha:1]];
[cell setSelectedBackgroundView:bgColorView];
UIColor *backColor = [UIColor colorWithRed:0 green:0 blue:1 alpha:1];
cell.backgroundColor = backColor;
UIColor *foreColor = [UIColor colorWithWhite:1 alpha:1];
cell.textLabel.textColor = foreColor;
cell.textLabel.text = @"row0";
}
else if ([indexPath row] == 1)
{
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIColor *backColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
cell.backgroundColor = backColor;
UIColor *foreColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
cell.textLabel.textColor = foreColor;
cell.textLabel.text = @"row1";
}
else if ([indexPath row] == 2)
{
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIColor *backColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
cell.backgroundColor = backColor;
UIColor *foreColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
cell.textLabel.textColor = foreColor;
cell.textLabel.text = @"row2";
}
return cell;
}
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:[indexPath section]];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:path];
[cell setSelectionStyle:UITableViewCellSelectionStyleBlue];
[tableView selectRowAtIndexPath:path animated:YES scrollPosition:UITableViewScrollPositionNone];
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tvStat cellForRowAtIndexPath:indexPath];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
#pragma mark Table view Gestures
-(IBAction)singleTapFrom:(UIGestureRecognizer *)tapRecog
{
CGPoint tapLoc = [tapRecog locationInView:tvStat];
NSIndexPath *tapPath = [tvStat indexPathForRowAtPoint:tapLoc];
NSIndexPath *seleRow = [tvStat indexPathForSelectedRow];
if([seleRow section] != [tapPath section])
[self tableView:tvStat didDeselectRowAtIndexPath:seleRow];
else if (seleRow == nil )
{}
else if([seleRow section] == [tapPath section] || [seleRow length] != 0)
return;
if(!tapPath)
[self.view endEditing:YES];
[self tableView:tvStat didSelectRowAtIndexPath:tapPath];
}
Ich benutze unten Ansatz und funktioniert gut für mich,
class MyTableViewCell : UITableViewCell {
var defaultStateColor:UIColor?
var hitStateColor:UIColor?
override func awakeFromNib(){
super.awakeFromNib()
self.selectionStyle = .None
}
// if you are overriding init you should set selectionStyle = .None
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let hitColor = hitStateColor {
self.contentView.backgroundColor = hitColor
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let defaultColor = defaultStateColor {
self.contentView.backgroundColor = defaultColor
}
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
if let defaultColor = defaultStateColor {
self.contentView.backgroundColor = defaultColor
}
}
}
[cell setSelectionStyle:UITableViewCellSelectionStyleGray];
Stellen Sie sicher, dass Sie die obige Zeile verwendet haben, um den Auswahleffekt zu verwenden
Es ist einfach, wenn der Tabellenansichtsstil einfach ist, aber im Gruppenstil ist es ein kleines Problem. Ich löse es durch:
CGFloat cellHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kGroupTableViewCellWidth+2, cellHeight)];
view.backgroundColor = kCommonHighlightedColor;
cell.selectedBackgroundView = view;
[view release];
UIRectCorner cornerFlag = 0;
CGSize radii = CGSizeMake(0, 0);
NSInteger theLastRow = --> (yourDataSourceArray.count - 1);
if (indexPath.row == 0) {
cornerFlag = UIRectCornerTopLeft | UIRectCornerTopRight;
radii = CGSizeMake(10, 10);
} else if (indexPath.row == theLastRow) {
cornerFlag = UIRectCornerBottomLeft | UIRectCornerBottomRight;
radii = CGSizeMake(10, 10);
}
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:cornerFlag cornerRadii:radii];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = maskPath.CGPath;
view.layer.mask = shapeLayer;
kGroupTableViewCellWidth, ich definiere es als 300, es ist die Breite der Zellenbreite der Gruppentabellenansicht im iPhone
override func setSelected(selected: Bool, animated: Bool) {
// Configure the view for the selected state
super.setSelected(selected, animated: animated)
let selView = UIView()
selView.backgroundColor = UIColor( red: 5/255, green: 159/255, blue:223/255, alpha: 1.0 )
self.selectedBackgroundView = selView
}
Versuchen Sie folgenden Code.
- (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;
}
// schnelle Version:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
cell.selectedBackgroundView = UIImageView()
cell.backgroundView=UIImageView()
let selectedBackground : UIImageView = cell.selectedBackgroundView as! UIImageView
selectedBackground.image = UIImage.init(named:"selected.png");
let backGround : UIImageView = cell.backgroundView as! UIImageView
backGround.image = UIImage.init(named:"defaultimage.png");
return cell
}
Ich benutze iOS 9.3 und stelle die Farbe über das Storyboard ein oder setze cell.selectionStyle
hat bei mir nicht funktioniert, aber der folgende Code hat funktioniert:
UIView *customColorView = [[UIView alloc] init];
customColorView.backgroundColor = [UIColor colorWithRed:55 / 255.0
green:141 / 255.0
blue:211 / 255.0
alpha:1.0];
cell.selectedBackgroundView = customColorView;
return cell;
Ich habe diese Lösung gefunden hier .