UITableView: cambia il colore dell'intestazione della sezione
-
03-07-2019 - |
Domanda
Come posso cambiare il colore di un'intestazione di sezione in UITableView?
EDIT : la risposta fornita da DJ-S dovrebbe essere considerata per iOS 6 e sopra. La risposta accettata non è aggiornata.
Soluzione
Speriamo che questo metodo dal protocollo UITableViewDelegate
ti inizi:
Objective-C:
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease];
if (section == integerRepresentingYourSectionOfInterest)
[headerView setBackgroundColor:[UIColor redColor]];
else
[headerView setBackgroundColor:[UIColor clearColor]];
return headerView;
}
Swift:
func tableView(_ tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView!
{
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 30))
if (section == integerRepresentingYourSectionOfInterest) {
headerView.backgroundColor = UIColor.redColor()
} else {
headerView.backgroundColor = UIColor.clearColor()
}
return headerView
}
Aggiornato 2017:
Swift 3:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 30))
if (section == integerRepresentingYourSectionOfInterest) {
headerView.backgroundColor = UIColor.red
} else {
headerView.backgroundColor = UIColor.clear
}
return headerView
}
Sostituisci [UIColor redColor]
con qualunque UIColor
desideri. Potresti anche voler regolare le dimensioni di headerView
.
Altri suggerimenti
Questa è una vecchia domanda, ma penso che la risposta debba essere aggiornata.
Questo metodo non implica la definizione e la creazione di una vista personalizzata. In iOS 6 e versioni successive, puoi facilmente cambiare il colore di sfondo e il colore del testo definendo
-(void)tableView:(UITableView *)tableView
willDisplayHeaderView:(UIView *)view
forSection:(NSInteger)section
metodo delegato sezione
Ad esempio:
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
// Background color
view.tintColor = [UIColor blackColor];
// Text Color
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
[header.textLabel setTextColor:[UIColor whiteColor]];
// Another way to set the background color
// Note: does not preserve gradient effect of original header
// header.contentView.backgroundColor = [UIColor blackColor];
}
Tratto dal mio post qui: https://happyteamlabs.com/ blog / ios-how da personalizzare-tavolo-view-header-e-footer-colori /
Swift 3/4
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
view.tintColor = UIColor.red
let header = view as! UITableViewHeaderFooterView
header.textLabel?.textColor = UIColor.white
}
Ecco come cambiare il colore del testo.
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(10, 3, tableView.bounds.size.width - 10, 18)] autorelease];
label.text = @"Section Header Text Here";
label.textColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.75];
label.backgroundColor = [UIColor clearColor];
[headerView addSubview:label];
Puoi farlo se vuoi un'intestazione con colore personalizzato:
[[UITableViewHeaderFooterView appearance] setTintColor:[UIColor redColor]];
Questa soluzione funziona benissimo da iOS 6.0.
La seguente soluzione funziona con Swift 1.2 con iOS 8+
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// This changes the header background
view.tintColor = UIColor.blueColor()
// Gets the header view as a UITableViewHeaderFooterView and changes the text colour
var headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
headerView.textLabel.textColor = UIColor.redColor()
}
Non dimenticare di aggiungere questo pezzo di codice dal delegato o la tua vista sarà tagliata o apparirà dietro il tavolo in alcuni casi, relativamente all'altezza della tua vista / etichetta.
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 30;
}
Se non vuoi creare una vista personalizzata, puoi anche cambiare il colore in questo modo (richiede iOS 6):
-(void) tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
if ([view isKindOfClass: [UITableViewHeaderFooterView class]]) {
UITableViewHeaderFooterView* castView = (UITableViewHeaderFooterView*) view;
UIView* content = castView.contentView;
UIColor* color = [UIColor colorWithWhite:0.85 alpha:1.]; // substitute your color here
content.backgroundColor = color;
}
}
L'impostazione del colore di sfondo su UITableViewHeaderFooterView è diventata obsoleta. Utilizzare invece contentView.backgroundColor
.
Imposta lo sfondo e il colore del testo dell'area della sezione: (Grazie a William Jockusch
e Dj S
)
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
if ([view isKindOfClass: [UITableViewHeaderFooterView class]]) {
UITableViewHeaderFooterView* castView = (UITableViewHeaderFooterView*) view;
castView.contentView.backgroundColor = [UIColor grayColor];
[castView.textLabel setTextColor:[UIColor grayColor]];
}
}
Swift 4
Per cambiare il colore di sfondo , colore dell'etichetta di testo e carattere per la vista dell'intestazione di una sezione UITableView, basta semplicemente ignorare willDisplayHeaderView
per la visualizzazione della tabella in questo modo:
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
header.backgroundView?.backgroundColor = .white
header.textLabel?.textColor = .black
header.textLabel?.font = UIFont(name: "Helvetica-Bold", size: 14)
}
Questo ha funzionato perfettamente per me; spero che ti aiuti anche tu!
Ecco come aggiungere un'immagine nella vista dell'intestazione:
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease];
UIImageView *headerImage = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"top-gery-bar.png"]] autorelease];
headerImage.frame = CGRectMake(0, 0, tableView.bounds.size.width, 30);
[headerView addSubview:headerImage];
return headerView;
}
Per iOS8 (Beta) e Swift scegli il colore RGB desiderato e prova questo:
override func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! {
var header :UITableViewHeaderFooterView = UITableViewHeaderFooterView()
header.contentView.backgroundColor = UIColor(red: 254.0/255.0, green: 190.0/255.0, blue: 127.0/255.0, alpha: 1)
return header
}
(Il "override" è presente poiché sto usando UITableViewController invece di un normale UIViewController nel mio progetto, ma non è obbligatorio per cambiare il colore dell'intestazione della sezione)
Il testo dell'intestazione sarà ancora visualizzato. Tieni presente che dovrai regolare l'altezza dell'intestazione della sezione.
Buona fortuna.
SWIFT 2
Sono stato in grado di cambiare con successo il colore di sfondo della sezione con un effetto di sfocatura aggiunto (che è davvero fantastico). Per cambiare facilmente il colore di sfondo della sezione:
- Prima vai su Storyboard e seleziona la vista tabella
- Vai a Controllo attributi
- Voce di elenco
- Scorri verso il basso fino a Visualizza
- Modifica " Sfondo "
Quindi, per l'effetto sfocatura, aggiungi al codice:
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// This is the blur effect
let blurEffect = UIBlurEffect(style: .Light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
// Gets the header view as a UITableViewHeaderFooterView and changes the text colour and adds above blur effect
let headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
headerView.textLabel!.textColor = UIColor.darkGrayColor()
headerView.textLabel!.font = UIFont(name: "HelveticaNeue-Light", size: 13)
headerView.tintColor = .groupTableViewBackgroundColor()
headerView.backgroundView = blurEffectView
}
So che ha una risposta, per ogni evenienza, in Swift usa quanto segue
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let tableViewWidth = self.tableView.bounds
let headerView = UIView(frame: CGRectMake(0, 0, tableViewWidth.size.width, self.tableView.sectionHeaderHeight))
headerView.backgroundColor = UIColor.greenColor()
return headerView
}
iOS 8+
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
tableView.tableHeaderView?.backgroundColor = UIColor.blue()
}
Basato sulla risposta di @Dj S, usando Swift 3. Funziona benissimo su iOS 10.
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// Background color
view.tintColor = UIColor.black
// Text Color
let headerView = view as! UITableViewHeaderFooterView
headerView.textLabel?.textColor = UIColor.white
}
Ho un progetto che utilizza celle di visualizzazione di tabelle statiche, in iOS 7.x. willDisplayHeaderView non si attiva. Tuttavia, questo metodo funziona bene:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
NSLog(@"%s", __FUNCTION__);
CGRect headerFrame = CGRectMake(x, y, w, h);
UIView *headerView = [[UIView alloc] initWithFrame:headerFrame];
headerView.backgroundColor = [UIColor blackColor];
-(void) tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view
forSection:(NSInteger)section
{
if ([view isKindOfClass: [UITableViewHeaderFooterView class]])
{
UITableViewHeaderFooterView *castView = (UITableViewHeaderFooterView *) view;
UIView *content = castView.contentView;
UIColor *color = [UIColor whiteColor]; // substitute your color here
content.backgroundColor = color;
[castView.textLabel setTextColor:[UIColor blackColor]];
}
}
Penso che questo codice non sia così male.
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(MyHeaderView.reuseIdentifier) as MyHeaderView
let backgroundView = UIView()
backgroundView.backgroundColor = UIColor.whiteColor()
headerView.backgroundView = backgroundView
headerView.textLabel.text = "hello"
return headerView
}
In iOS 7.0.4 ho creato un'intestazione personalizzata con il proprio XIB. Nulla di menzionato qui prima ha funzionato. Doveva essere la sottoclasse di UITableViewHeaderFooterView per funzionare con dequeueReusableHeaderFooterViewWithIdentifier:
e sembra che la classe sia molto testarda per quanto riguarda il colore di sfondo. Quindi alla fine ho aggiunto un UIView (potresti farlo con codice o IB) con il nome customBackgroudView, e quindi ho impostato la proprietà backgroundColor. In layoutSubviews: ho impostato la cornice di quella vista su limiti. Funziona con iOS 7 e non presenta anomalie.
// in MyTableHeaderView.xib drop an UIView at top of the first child of the owner
// first child becomes contentView
// in MyTableHeaderView.h
@property (nonatomic, weak) IBOutlet UIView * customBackgroundView;
// in MyTableHeaderView.m
-(void)layoutSubviews;
{
[super layoutSubviews];
self.customBackgroundView.frame = self.bounds;
}
// if you don't have XIB / use IB, put in the initializer:
-(id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
...
UIView * customBackgroundView = [[UIView alloc] init];
[self.contentView addSubview:customBackgroundView];
_customBackgroundView = customBackgroundView;
...
}
// in MyTableViewController.m
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
MyTableHeaderView * header = [self.tableView
dequeueReusableHeaderFooterViewWithIdentifier:@"MyTableHeaderView"];
header.customBackgroundView.backgroundColor = [UIColor redColor];
return header;
}
Basta cambiare il colore del livello della vista dell'intestazione
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease]; headerView.layer.backgroundColor = [UIColor clearColor].CGColor }
Se qualcuno ha bisogno di rapidità, mantiene il titolo:
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0,y: 0,width: self.tableView.frame.width, height: 30))
view.backgroundColor = UIColor.redColor()
let label = UILabel(frame: CGRect(x: 15,y: 5,width: 200,height: 25))
label.text = self.tableView(tableView, titleForHeaderInSection: section)
view.addSubview(label)
return view
}
Nel mio caso, ha funzionato in questo modo:
let headerIdentifier = "HeaderIdentifier"
let header = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: headerIdentifier)
header.contentView.backgroundColor = UIColor.white
Basta impostare il colore di sfondo della vista di sfondo:
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
let tableHeader = view as! UITableViewHeaderFooterView
tableHeader.backgroundView?.backgroundColor = UIColor.white
}
Con RubyMotion / RedPotion, incollalo nella TableScreen:
def tableView(_, willDisplayHeaderView: view, forSection: section)
view.textLabel.textColor = rmq.color.your_text_color
view.contentView.backgroundColor = rmq.color.your_background_color
end
Funziona come un fascino!
Ho ricevuto un messaggio da Xcode attraverso il registro della console
[TableView] Attivazione del colore di sfondo UITableViewHeaderFooterView è stato deprecato. Si prega di impostare un'abitudine Visualizza con il colore di sfondo desiderato sullo sfondo proprietà invece.
Quindi creo un nuovo UIView e lo poso come sfondo di HeaderView. Non è una buona soluzione ma è facile come diceva Xcode.
Sebbene func tableView (_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
funzionerà pure, puoi ottenerlo senza implementare un altro metodo delegato.
in te func tableView (_ tableView: UITableView, sezione viewForHeaderInSection: Int) - > UIView?
, puoi usare view.contentView.backgroundColor = UIColor.white
invece di view.backgroundView? .BackgroundColor = UIColor.white
che non funziona . (So ??che backgroundView
è facoltativo, ma anche quando è lì, questo non si sveglia senza implementare willDisplayHeaderView
Usando UIAppearance puoi cambiarlo per tutte le intestazioni nella tua applicazione in questo modo:
UITableViewHeaderFooterView.appearance (). backgroundColor = theme.subViewBackgroundColor
Swift 4 lo rende molto semplice. Basta aggiungere questo alla tua classe e impostare il colore secondo necessità.
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.backgroundColor = UIColor(red: 0.094, green: 0.239, blue: 0.424, alpha: 1.0)
}
o se un colore semplice
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.backgroundColor = UIColor.white
}