UITableView - change la couleur de l'en-tête de la section
-
03-07-2019 - |
Question
Comment changer la couleur d'un en-tête de section dans UITableView?
MODIFIER : la réponse fournie par DJ-S doit être prise en compte pour iOS 6 et au dessus de. La réponse acceptée est obsolète.
La solution
Espérons que cette méthode du protocole UITableViewDelegate
vous permettra de démarrer:
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
}
Mise à jour en 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
}
Remplacez [UIColor redColor]
par le UIColor
de votre choix. Vous pouvez également souhaiter ajuster les dimensions de headerView
.
Autres conseils
Ceci est une vieille question, mais je pense que la réponse doit être mise à jour.
Cette méthode n’implique pas la définition et la création de votre propre vue personnalisée. Dans iOS 6 et versions supérieures, vous pouvez facilement modifier la couleur d'arrière-plan et la couleur du texte en définissant la
-(void)tableView:(UITableView *)tableView
willDisplayHeaderView:(UIView *)view
forSection:(NSInteger)section
méthode de délégation de section
Par exemple:
- (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];
}
Extrait de mon post ici: https://happyteamlabs.com/ blog / ios-comment-personnaliser-table-vue-en-tête-et-pied de page-couleurs /
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
}
Voici comment changer la couleur du texte.
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];
Vous pouvez le faire si vous voulez un en-tête de couleur personnalisée:
[[UITableViewHeaderFooterView appearance] setTintColor:[UIColor redColor]];
Cette solution fonctionne parfaitement depuis iOS 6.0.
La solution suivante fonctionne pour Swift 1.2 avec 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()
}
N'oubliez pas d'ajouter cette partie de code du délégué, sinon votre vue sera coupée ou apparaît derrière la table dans certains cas, par rapport à la hauteur de votre vue / libellé.
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 30;
}
Si vous ne souhaitez pas créer une vue personnalisée, vous pouvez également modifier la couleur de la manière suivante (nécessite 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;
}
}
La définition de la couleur d'arrière-plan sur UITableViewHeaderFooterView est obsolète. Veuillez utiliser contentView.backgroundColor
à la place.
Définissez la couleur de fond et de texte de la section: (Merci à William Jockusch
et à 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
Pour modifier la couleur d'arrière-plan , la couleur de l'étiquette du texte et la police de la vue d'en-tête d'une section UITableView, remplacez simplement willDisplayHeaderView.
pour votre vue de table comme suit:
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)
}
Cela a parfaitement fonctionné pour moi; espérons que cela vous aidera aussi!
Voici comment ajouter une image dans la vue d'en-tête:
- (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;
}
Pour iOS8 (bêta) et Swift, choisissez la couleur RVB souhaitée et essayez ceci:
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
}
(Le "remplacement" existe depuis que j'utilise le UITableViewController au lieu d'un UIViewController normal dans mon projet, mais ce n'est pas obligatoire pour changer la couleur de l'en-tête de la section)
Le texte de votre en-tête sera toujours visible. Notez que vous devrez ajuster la hauteur de l'en-tête de la section.
Bonne chance.
SWIFT 2
J'ai réussi à changer la couleur d'arrière-plan de la section avec un effet de flou ajouté (ce qui est vraiment cool). Pour changer facilement la couleur de fond de la section:
- Allez d'abord dans le Storyboard et sélectionnez la vue Table
- Accédez à l'inspecteur d'attributs
- Élément de liste
- Faites défiler jusqu'à Affichage
- Modifier "Contexte"
Ensuite, pour un effet de flou, ajoutez au code:
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
}
Je connais sa réponse, juste au cas où, dans Swift, utilisez ce qui suit
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()
}
Basé sur la réponse @Dj S et utilisant Swift 3. Cela fonctionne très bien sur 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
}
J'ai un projet utilisant des cellules de vue de tableau statique dans iOS 7.x. willDisplayHeaderView ne se déclenche pas. Cependant, cette méthode fonctionne bien:
- (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]];
}
}
Je pense que ce code n'est pas si mal.
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
}
Dans iOS 7.0.4, j'ai créé un en-tête personnalisé avec son propre fichier XIB. Rien de mentionné ici avant travaillé. Ce devait être la sous-classe de UITableViewHeaderFooterView pour fonctionner avec le dequeueReusableHeaderFooterViewWithIdentifier:
et il semble que la classe soit très obstinée en ce qui concerne la couleur d'arrière-plan. Donc, finalement, j'ai ajouté un UIView (vous pouvez le faire avec du code ou IB) avec le nom customBackgroudView, puis définir sa propriété backgroundColor. Dans layoutSubviews: J'ai défini le cadre de cette vue sur des limites. Il fonctionne avec iOS 7 et ne pose aucun problème.
// 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;
}
Modifiez simplement la couleur de la couche de la vue d'en-tête
- (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 }
Si quelqu'un a besoin de rapide, conserve le titre:
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
}
Dans mon cas, cela a fonctionné comme ceci:
let headerIdentifier = "HeaderIdentifier"
let header = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: headerIdentifier)
header.contentView.backgroundColor = UIColor.white
Il suffit de définir la couleur d'arrière-plan de la vue d'arrière-plan:
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
let tableHeader = view as! UITableViewHeaderFooterView
tableHeader.backgroundView?.backgroundColor = UIColor.white
}
Avec RubyMotion / RedPotion, collez-le dans votre écran de table:
def tableView(_, willDisplayHeaderView: view, forSection: section)
view.textLabel.textColor = rmq.color.your_text_color
view.contentView.backgroundColor = rmq.color.your_background_color
end
Fonctionne comme un charme!
J'ai reçu un message de Xcode via le journal de la console
[TableView] Définition de la couleur d'arrière-plan UITableViewHeaderFooterView est obsolète. S'il vous plaît définir une coutume UIView avec la couleur d'arrière-plan souhaitée pour le backgroundView propriété à la place.
Ensuite, je crée simplement un nouveau UIView et le pose en arrière-plan de HeaderView. Ce n’est pas une bonne solution, mais c’est simple comme le disait Xcode.
Bien que func tableView (_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
fonctionne également, vous pouvez y parvenir sans implémenter une autre méthode de délégation.
dans vous func tableView (_ tableView: UITableView, section viewForHeaderInSection: Int) - > UIView?
, vous pouvez utiliser view.contentView.backgroundColor = UIColor.white
au lieu de view.backgroundView? .BackgroundColor = UIColor.white
qui ne fonctionne pas . (Je sais que backgroundView
est facultatif, mais même lorsqu'il est là, cela ne fonctionnera pas sans implémenter willDisplayHeaderView
En utilisant UIAppearance, vous pouvez le modifier pour tous les en-têtes de votre application, comme suit:
UITableViewHeaderFooterView.appearance (). backgroundColor = theme.subViewBackgroundColor
Swift 4 le rend très facile. Ajoutez-le simplement à votre classe et définissez la couleur selon vos besoins.
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)
}
ou si une couleur simple
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.backgroundColor = UIColor.white
}