UITableView - zmiana koloru nagłówka sekcji


Odpowiedzi:


393

Mamy nadzieję, że ta metoda z UITableViewDelegateprotokołu pozwoli Ci zacząć:

Cel 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;
}

Szybki:

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
}

Zaktualizowano 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
    }

Zamień na [UIColor redColor]dowolne UIColor. Możesz także dostosować wymiary headerView.


17
Może także pomóc w dostosowaniu rozmiaru nagłówka sekcji za pomocą self.tableView.sectionHeaderHeight. W przeciwnym razie możesz mieć problem z wyświetleniem tekstu wyświetlanego dla tytułu sekcji.
— Tony Lenzi

Współpracuje z [UIColor xxxColor]jednak gdy próbuję kolor niestandardowy, jak te, które można uzyskać z programu Photoshop (tak użyciu UIColor red:green:blue:alpha:, jest to po prostu biały robię coś złego.?
— Matej

Napisz osobne pytanie, a my postaramy się pomóc. Dołącz kod źródłowy.
— Alex Reynolds,

12
Pamiętaj, że ta odpowiedź (poprawna) po prostu zwróci UIView bez zawartości.
— Greg M. Krsak

7
To dość nieaktualne informacje, a samo utworzenie innego widoku nie jest najlepszą odpowiedzią. Chodzi o to, aby uzyskać właściwy widok i zmienić na nim kolor lub odcień. Odpowiedź poniżej przy użyciu willDisplayHeaderView jest znacznie lepszym podejściem.
— Alex Zavatone

741

To stare pytanie, ale myślę, że odpowiedź wymaga aktualizacji.

Ta metoda nie obejmuje definiowania i tworzenia własnego widoku niestandardowego. W iOS 6 i nowszych można łatwo zmienić kolor tła i kolor tekstu, definiując

-(void)tableView:(UITableView *)tableView 
    willDisplayHeaderView:(UIView *)view 
    forSection:(NSInteger)section

metoda delegowania sekcji

Na przykład:

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

Zaczerpnięte z mojego postu tutaj: https://happyteamlabs.com/blog/ios-how-to-customize-table-view-header-and-footer-colors/

Szybki 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
}

2
Nie miałem pojęcia, że ​​to nawet zostało dodane do SDK. Znakomity! Absolutnie poprawna odpowiedź.
— JRod

1
OP - Zaktualizuj zaakceptowaną odpowiedź na to. Znacznie czystsze niż stare podejścia.
— Kyle Clegg

10
To chyba nie działa dla mnie. Kolor tekstu działa, ale nie ma odcienia tła nagłówka. Jestem na iOS 7.0.4
— zeeple

10
user1639164, możesz użyć header.backgroundView.backgroundColor = [UIColor blackColor]; ustawić odcień tła nagłówka.
— 慭 慭 流 觞

2
@Kent minęło już trochę czasu, ale dla przyszłych ludzi header.contentView.backgroundColor = [UIColor blackColor];opcja da ci nieprzejrzysty nagłówek
— SparkyRobinson

98

Oto jak zmienić kolor tekstu.

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];

18
Dzięki DoctorG - Przydało się. BTW - aby zachować istniejącą etykietę dostarczoną przez źródło danych, zmodyfikowałem drugą linię w następujący sposób: label.text = [tableView.dataSource tableView: tableView titleForHeaderInSection: sekcja]; Może to być zła forma, ale zadziałało dla mnie. Może to może pomóc komuś innemu.
— JJ Rohrer

1
@JJ Ta forma jest właściwie w porządku, ponieważ wywołujesz tę samą metodę, której początkowo użyłeś do zdefiniowania nagłówka sekcji tabeli.
— Tim

3
Usunąłem autorelease i zmieniłem na jawną wersję. Metody formatowania UITableView są nazywane wiele, wiele razy. Jeśli to możliwe, unikaj automatycznego uwalniania.
— memmons,

@Harkonian, zamiast zmieniać przesłaną odpowiedź, zalecamy zmianę komentarza do odpowiedzi. Za zmianę uważa się kod innej osoby za pomocą edycji. Błędy ortograficzne oraz złe formatowanie i gramatyka to uczciwa gra.
— Tin Man

1
Zamiast addSubview: UILabel, powinieneś po prostu zwracać UILabel w viewForHeaderInSection. UILable is-a UIView już :)
— Nas Banov

52

Możesz to zrobić, jeśli chcesz nagłówek z niestandardowym kolorem:

[[UITableViewHeaderFooterView appearance] setTintColor:[UIColor redColor]];

To rozwiązanie działa świetnie od iOS 6.0.


1
hm ... to nie działa dla mnie. wypróbowałem symulator iOS 6 i urządzenie iOS 7. Testowałeś w ten sposób? Gdzie mam to umieścić?
— Maxim Kholyavkin

Można to zrobić w aplikacji: didFinishLaunchingWithOptions: metoda delegowania aplikacji.
— Leszek Zarna

moja wina: Próbowałem użyć w ten sposób podczas UITableViewStyleGrouped BTW: aby zmienić kolor tekstu w ten sposób należy użyć stackoverflow.com/a/20778406/751932
— Maxim Kholyavkin

Jeśli jest w niestandardowym UIView, po prostu wstaw go - metoda init.
— felixwcf

31

Poniższe rozwiązanie działa dla Swift 1.2 z 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()

}

22

Ustawienie koloru tła w UITableViewHeaderFooterView jest przestarzałe. Użyj contentView.backgroundColorzamiast tego.


21

Nie zapomnij dodać tego fragmentu kodu od delegata, w przeciwnym razie twój widok zostanie odcięty lub pojawi się za stołem, w zależności od wysokości twojego widoku / etykiety.

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

Nie jest to już potrzebne, jeśli korzystasz z iOS6 i późniejszej odpowiedzi Dj S.
— Bjinse

21

Możesz to zrobić na main.storyboard w około 2 sekundy.

  1. Wybierz Widok tabeli
  2. Idź do Inspektora atrybutów
  3. Element listy
  4. Przewiń w dół do Wyświetl podtytuły
  5. Zmień tło"

Spójrz tutaj


18

Jeśli nie chcesz tworzyć widoku niestandardowego, możesz również zmienić kolor w ten sposób (wymaga 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;
    }
}

13

Ustaw kolor tła i tekstu obszaru przekroju: (Dzięki William Jockuschi 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]];
    }
}

13

Szybki 4

Aby zmienić kolor tła , kolor tekstu etykiet i czcionki dla widoku nagłówku UITableView sekcji, wystarczy zastąpić willDisplayHeaderViewdla widoku tabeli tak:

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)
} 

To działało idealnie dla mnie; mam nadzieję, że ci to pomoże!


Ustawienie koloru tła w UITableViewHeaderFooterView jest przestarzałe. Zamiast tego należy ustawić niestandardowy UIView z pożądanym kolorem tła na właściwość backgroundView.
— mojtaba al moussawi

10

Oto jak dodać obraz w widoku nagłówka:

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

8

W systemie iOS8 (Beta) i Swift wybierz żądany kolor RGB i wypróbuj to:

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

}

(„Zastąpienie” istnieje, ponieważ w moim projekcie używam UITableViewController zamiast normalnego UIViewController, ale nie jest to obowiązkowe do zmiany koloru nagłówka sekcji)

Tekst nagłówka nadal będzie widoczny. Pamiętaj, że musisz dostosować wysokość nagłówka sekcji.

Powodzenia.


6

SWIFT 2

Z powodzeniem mogłem zmienić kolor tła przekroju z dodanym efektem rozmycia (co jest naprawdę fajne). Aby łatwo zmienić kolor tła sekcji:

  1. Najpierw przejdź do Storyboard i wybierz Widok tabeli
  2. Idź do Inspektora atrybutów
  3. Element listy
  4. Przewiń w dół do Wyświetl
  5. Zmień tło"

Następnie, aby uzyskać efekt rozmycia, dodaj do kodu:

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

}

5

Wiem, że udzielono odpowiedzi, na wszelki wypadek. W Swift użyj następujących

    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
    }

4

iOS 8+

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        tableView.tableHeaderView?.backgroundColor = UIColor.blue()
}

4

Na podstawie odpowiedzi @Dj S przy użyciu Swift 3. Działa to świetnie na 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
}

3

Mam projekt wykorzystujący statyczne komórki widoku tabeli w iOS 7.x. willDisplayHeaderView nie uruchamia się. Jednak ta metoda działa dobrze:

- (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];

3
 -(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]];
        }
 }

3

Myślę, że ten kod nie jest taki zły.

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
}

3

Swift 4 sprawia, że ​​jest to bardzo łatwe. Po prostu dodaj to do swojej klasy i ustaw kolor według potrzeb.

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)
    }

lub jeśli prosty kolor

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        view.backgroundColor = UIColor.white
    }

Zaktualizowano dla Swift 5

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        view.tintColor = UIColor(red: 0.094, green: 0.239, blue: 0.424, alpha: 1.0)
    }

lub jeśli prosty kolor

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        view.tintColor = UIColor.white
    }

4
w iOS 13 zamień „view.backgroundColor” na „view.tintColor”.
— Bogdan Razvan

2

W iOS 7.0.4 utworzyłem niestandardowy nagłówek z własnym XIB. Nic tu wcześniej nie wspomniano. Musiała być podklasą UITableViewHeaderFooterView do pracy z, dequeueReusableHeaderFooterViewWithIdentifier:i wydaje się, że klasa jest bardzo uparta jeśli chodzi o kolor tła. W końcu dodałem UIView (można to zrobić za pomocą kodu lub IB) o nazwie customBackgroudView, a następnie ustawiłem jego właściwość backgroundColor. W layoutSubviews: Ustawiłem ramkę tego widoku na granice. Działa z iOS 7 i nie powoduje żadnych usterek.

// 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;
}

2

Wystarczy zmienić kolor warstwy widoku nagłówka

- (UIView *) tableView: (UITableView *) tableView viewForHeaderInSection: sekcja (NSInteger) 
{
  UIView * headerView = [[[Przydział UIView] initWithFrame: CGRectMake (0, 0, tableView.bounds.size.width, 30)] autorelease];
 headerView.layer.backgroundColor = [UIColor clearColor] .CGColor
}


2

Jeśli ktoś potrzebuje szybkiego, zachowuje tytuł:

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
}

2

Dostałem wiadomość od Xcode poprzez log konsoli

[TableView] Ustawienie koloru tła w UITableViewHeaderFooterView jest przestarzałe. Zamiast tego ustaw niestandardowy UIView z pożądanym kolorem tła na właściwość backgroundView.

Następnie po prostu tworzę nowy UIView i kładę go jako tło HeaderView. Nie jest to dobre rozwiązanie, ale jest łatwe, jak powiedział Xcode.


2

W moim przypadku działało to tak:

let headerIdentifier = "HeaderIdentifier"
let header = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: headerIdentifier)
header.contentView.backgroundColor = UIColor.white

2

Wystarczy ustawić kolor tła widoku tła:

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){         
  let tableHeader = view as! UITableViewHeaderFooterView        
  tableHeader.backgroundView?.backgroundColor = UIColor.white     
}

1

Z RubyMotion / RedPotion, wklej to do swojego TableScreen:

  def tableView(_, willDisplayHeaderView: view, forSection: section)
    view.textLabel.textColor = rmq.color.your_text_color
    view.contentView.backgroundColor = rmq.color.your_background_color
  end

Działa jak marzenie!


1

Dla szybkiego 5+

W willDisplayHeaderViewmetodzie

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

     //For Header Background Color
     view.tintColor = .black

    // For Header Text Color
    let header = view as! UITableHeaderFooterView
    header.textLabel?.textColor = .white
}

Mam nadzieję, że to Ci pomoże :]


0

Chociaż func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)będzie również działać, możesz to osiągnąć bez implementacji innej metody delegowania. w twojej func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?metodzie możesz użyć view.contentView.backgroundColor = UIColor.whitezamiast, view.backgroundView?.backgroundColor = UIColor.whitektóra nie działa. (Wiem, że backgroundViewjest to opcjonalne, ale nawet jeśli tam jest, nie budzi się bez wdrożeniawillDisplayHeaderView

Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.