Dostosuj sekcję nagłówka UITableView

Chcę dostosować UITableView Nagłówek dla każdej sekcji. Do tej pory zaimplementowałem

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

Ta UITabelViewDelegate metoda. Co chcę zrobić, to pobrać bieżący nagłówek dla każdej sekcji i po prostu dodać UILabel jako subview.

Jak na razie nie jestem w stanie tego osiągnąć. Ponieważ nie mogłem znaleźć niczego, aby uzyskać domyślny nagłówek sekcji. Pierwsze pytanie, czy jest jakiś sposób na uzyskanie domyślnego nagłówka sekcji ?

Jeśli nie jest to możliwe, muszę utworzyć widok kontenera, który jest UIView ale tym razem muszę ustawić domyślny kolor tła, kolor cienia itp. Ponieważ, jeśli przyjrzysz się uważnie nagłówkowi sekcji, jest on już dostosowany.

Jak mogę uzyskać te wartości domyślne dla każdego nagłówka sekcji ?

Dziękuję wszystkim.
Author: Simple Maurya, 2013-03-25

20 answers

Możesz spróbować tego:

 -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 18)];
    /* Create custom view to display section header... */
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, tableView.frame.size.width, 18)];
    [label setFont:[UIFont boldSystemFontOfSize:12]];
     NSString *string =[list objectAtIndex:section];
    /* Section header is in 0th index... */
    [label setText:string];
    [view addSubview:label];
    [view setBackgroundColor:[UIColor colorWithRed:166/255.0 green:177/255.0 blue:186/255.0 alpha:1.0]]; //your background color...
    return view;
}
 267
Author: Lochana Ragupathy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-29 20:06:02

Wybrana odpowiedź za pomocą tableView :viewForHeaderInSection: jest poprawna.

Żeby podzielić się napiwkiem.

Jeśli używasz storyboard / xib, możesz utworzyć inną prototypową komórkę i użyć jej do "komórki sekcji". Kod do konfiguracji nagłówka jest podobny do sposobu konfiguracji komórek wiersza.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    static NSString *HeaderCellIdentifier = @"Header";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HeaderCellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:HeaderCellIdentifier];
    }

    // Configure the cell title etc
    [self configureHeaderCell:cell inSection:section];

    return cell;
}
 40
Author: samwize,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-05 06:38:33

Swift version of Lochana Tejas odpowiedź:

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 18))
    let label = UILabel(frame: CGRectMake(10, 5, tableView.frame.size.width, 18))
    label.font = UIFont.systemFontOfSize(14)
    label.text = list.objectAtIndex(indexPath.row) as! String
    view.addSubview(label)
    view.backgroundColor = UIColor.grayColor() // Set your background color

    return view
}
 28
Author: estemendoza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:23

Jeśli używasz domyślnego widoku nagłówka, możesz zmienić tylko tekst na nim za pomocą

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

Dla Swift:

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

Jeśli chcesz dostosować widok, musisz utworzyć nowy sam.

 17
Author: Mert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-01 11:14:58

Dlaczego nie użyć UITableViewHeaderFooterView?

 11
Author: user836773,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-28 15:44:21

Jeśli headerInSection nie jest pokaż, można spróbować tego.

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

Zwraca wysokość nagłówka danej sekcji.

 7
Author: Kathen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-29 01:59:27

Spróbuj tego......

override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) 
{
    // Background view is at index 0, content view at index 1
    if let bgView = view.subviews[0] as? UIView
    {
        // do your stuff
    }

    view.layer.borderColor = UIColor.magentaColor().CGColor
    view.layer.borderWidth = 1
}
 5
Author: Gigi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-06 05:32:26

Swift 3 wersja lochana i estemendoza odpowiedzi:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let view = UIView(frame: CGRect(x:0, y:0, width:tableView.frame.size.width, height:18))
    let label = UILabel(frame: CGRect(x:10, y:5, width:tableView.frame.size.width, height:18))
    label.font = UIFont.systemFont(ofSize: 14)
    label.text = "This is a test";
    view.addSubview(label);
    view.backgroundColor = UIColor.gray;
    return view

}

Należy również pamiętać, że należy również wdrożyć:

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 100;
}
 5
Author: Adam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-26 19:45:33
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    //put your values, this is part of my code
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 30.0f)];
    [view setBackgroundColor:[UIColor redColor]];
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, 150, 20)];
    [lbl setFont:[UIFont systemFontOfSize:18]];
    [lbl setTextColor:[UIColor blueColor]];
    [view addSubview:lbl];

    [lbl setText:[NSString stringWithFormat:@"Section: %ld",(long)section]];

    return view;
}
 4
Author: Boris Nikolić,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-06 05:33:37

Inne odpowiedzi dobrze sprawdzają się w odtwarzaniu domyślnego widoku nagłówka, ale nie odpowiadają na główne pytanie:

Czy jest jakiś sposób na uzyskanie domyślnego nagłówka sekcji ?

Jest sposób-wystarczy zaimplementować tableView:willDisplayHeaderView:forSection: w Twoim delegacie. Domyślny widok nagłówka zostanie przekazany do drugiego parametru, a stamtąd można go wrzucić do UITableViewHeaderFooterView a następnie dodaj / zmień podwizje, jak chcesz.

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;

    // Do whatever with the header view...
}
 3
Author: Craig Brown,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-28 22:26:25

Na Twoim miejscu stworzyłbym metodę, która zwraca UIView podany NSString do contain. Na przykład

+ (UIView *) sectionViewWithTitle:(NSString *)title;

W implementacji tej metody Utwórz UIView, Dodaj do niej UILabel z właściwościami, które chcesz ustawić, i oczywiście ustaw jej tytuł na podaną.

 2
Author: cpprulez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-25 09:32:01

Jest to najprostsze możliwe rozwiązanie. Poniższy kod może być użyty bezpośrednio do utworzenia niestandardowego nagłówka sekcji.

 -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    SectionHeaderTableViewCell *headerView = [tableView dequeueReusableCellWithIdentifier:@"sectionHeader"];

    //For creating a drop menu of rows from the section
    //==THIS IS JUST AN EXAMPLE. YOU CAN REMOVE THIS IF-ELSE.==
    if (![self.sectionCollapsedArray[section] boolValue])
    {
        headerView.imageView.image = [UIImage imageNamed:@"up_icon"];
    }
    else
    {
        headerView.imageView.image = [UIImage imageNamed:@"drop_icon"];
    }

    //For button action inside the custom cell
    headerView.dropButton.tag = section;
    [headerView.dropButton addTarget:self action:@selector(sectionTapped:) forControlEvents:UIControlEventTouchUpInside];

    //For removing long touch gestures.
    for (UIGestureRecognizer *recognizer in headerView.contentView.gestureRecognizers)
    {
        [headerView.contentView removeGestureRecognizer:recognizer];
        [headerView removeGestureRecognizer:recognizer];
    }

    return headerView.contentView;
}

Uwaga: SectionHeaderTableViewCell jest niestandardowym UITableViewCell utworzonym w Storyboard.

 2
Author: Anish Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-08 16:58:37
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    if([view isKindOfClass:[UITableViewHeaderFooterView class]]){

        UITableViewHeaderFooterView *headerView = view;

        [[headerView textLabel] setTextColor:[UIColor colorWithHexString:@"666666"]];
        [[headerView textLabel] setFont:[UIFont fontWithName:@"fontname" size:10]];
    }
}

Jeśli chcesz zmienić czcionkę etykiety tekstowej w nagłówku sekcji, chcesz to zrobić w willDisplayHeaderView. Aby ustawić tekst można to zrobić w viewForHeaderInSection lub titleForHeaderInSection. Powodzenia!

 2
Author: John Ottenlips,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-22 22:04:40

Magicznie dodaj nagłówek widoku tabeli w swift

Ostatnio próbowałem tego.

Potrzebowałem tylko jednego nagłówka w całym UITableView.

Jak chciałem UIImageView na górze widoku tabeli. Dodałem więc UIImageView na górze UITableViewCell i automatycznie został dodany jako tableViewHeader. Teraz podłączam ImageView do kontrolera ViewController i dodaję Obraz.

Byłem zdezorientowany, bo zrobiłem coś takiego po raz pierwszy. Więc do Wyczyść moje zamieszanie otwórz format xml tablicy głównej i znajdź widok obrazu został dodany jako nagłówek.

U mnie zadziałało. Dzięki xCode i swift.

 1
Author: Somir Saikia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-27 11:28:09

@samwize ' s solution in Swift (so upvote him!). Brilliant przy użyciu tego samego mechanizmu recyklingu również dla sekcji nagłówka/stopki:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let settingsHeaderSectionCell:SettingsHeaderSectionCell = self.dequeueReusableCell(withIdentifier: "SettingsHeaderSectionCell") as! SettingsHeaderSectionCell

    return settingsHeaderSectionCell
}
 1
Author: Javier Calatrava Llavería,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-03 11:02:42

Oprócz titleForHeaderInSection, możesz po prostu zmienić widok nagłówka, stopki. sprawdź mój komentarz tutaj: Zmień UITable section backgroundColor bez utraty tytułu sekcji

 0
Author: dimpiax,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:23

Jeśli chcesz tylko dodać tytuł do nagłówka tableView nie dodawaj widoku. W swift 3.x kod wygląda tak:

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    var lblStr = ""
    if section == 0 {
        lblStr = "Some String 1"
    }
    else if section == 1{
        lblStr = "Some String 2"
    }
    else{
        lblStr = "Some String 3"
    }
    return lblStr
}

Możesz zaimplementować tablicę, aby pobrać tytuł nagłówków.

 0
Author: abhishek chakrabartti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-20 06:40:30

Wracając do pierwotnego pytania (4 lata później), zamiast przebudowywać własny nagłówek sekcji, iOS może po prostu zadzwonić do Ciebie (z willDisplayHeaderView:forSection:) zaraz po zbudowaniu domyślnego. Na przykład chciałem dodać przycisk wykresu na prawej krawędzi nagłówka sekcji:

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    UITableViewHeaderFooterView * header = (UITableViewHeaderFooterView *) view;
    if (header.contentView.subviews.count >  0) return; //in case of reuse
    CGFloat rightEdge = CGRectGetMaxX(header.contentView.bounds);
    UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(rightEdge - 44, 0, 44, CGRectGetMaxY(header.contentView.bounds))];
    [button setBackgroundImage:[UIImage imageNamed:@"graphIcon"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(graphButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
}
 0
Author: mackworth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-08 16:06:16

Wywołanie metody delegata

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

return @"Some Title";
}

Daje to szansę na automatyczne dodanie domyślnego nagłówka z dynamicznym tytułem .

Możesz używać wielokrotnego użytku i dostosowywać nagłówek / stopkę .

Https://github.com/sourov2008/UITableViewCustomHeaderFooterSection

 0
Author: Sourov Datta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-27 19:00:36

Użyj tableView: willDisplayHeaderView:, aby dostosować widok, gdy ma być wyświetlany.

Daje to przewagę nad możliwością rozszerzenia widoku, który został już utworzony dla widoku nagłówka, zamiast konieczności samodzielnego odtwarzania całego widoku nagłówka.

Oto przykład, który koloruje sekcję nagłówka w oparciu o BOOL i dodaje szczegółowy element tekstowy do nagłówka.

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
//    view.tintColor = [UIColor colorWithWhite:0.825 alpha:1.0]; // gray
//    view.tintColor = [UIColor colorWithRed:0.825 green:0.725 blue:0.725 alpha:1.0]; // reddish
//    view.tintColor = [UIColor colorWithRed:0.925 green:0.725 blue:0.725 alpha:1.0]; // pink

    // Conditionally tint the header view
    BOOL isMyThingOnOrOff = [self isMyThingOnOrOff];

    if (isMyThingOnOrOff) {
        view.tintColor = [UIColor colorWithRed:0.725 green:0.925 blue:0.725 alpha:1.0];
    } else {
        view.tintColor = [UIColor colorWithRed:0.925 green:0.725 blue:0.725 alpha:1.0];
    }

    /* Add a detail text label (which has its own view to the section header… */
    CGFloat xOrigin = 100; // arbitrary
    CGFloat hInset = 20;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(xOrigin + hInset, 5, tableView.frame.size.width - xOrigin - (hInset * 2), 22)];

    label.textAlignment = NSTextAlignmentRight;

    [label setFont:[UIFont fontWithName:@"Helvetica-Bold" size:14.0]
    label.text = @"Hi.  I'm the detail text";

    [view addSubview:label];
}
 0
Author: Alex Zavatone,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-09 00:15:35