Изменить UITable раздел backgroundColor без потери заголовка раздела - PullRequest
7 голосов
/ 07 декабря 2011

Я изменил backgroundColor / backgroundImage моих разделов таблиц.
Я использую обычный tableView.Не беспокойтесь, работайте без проблем с этим кодом:

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *sectionView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 728, 40)] autorelease];
sectionView.backgroundColor = [UIColor greenColor];

//For using an image use this:
//sectionView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"whiteBackground.png"]];

return sectionView;
}  

Проблема сейчас в том, название раздела исчезло.

Я задаю название разделас этим кодом:

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

if ([tableView isEqual:self.searchDisplayController.searchResultsTableView]){
    return @"";
} else {    
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo name];
}


}

я получаю заголовки разделов, если не пользуюсь

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

Нужна ваша помощь.
Большое спасибо.

РЕДАКТИРОВАТЬ 1:

Благодаря Mutix:

в моем случае ответ будет:

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




UIView *sectionView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 728, 20)] autorelease];
sectionView.backgroundColor = [UIColor greenColor];

//sectionView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"whiteBackground.png"]];

//Add label to view
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 728, 20)];
titleLabel.backgroundColor = [UIColor clearColor];

//section Title
if ([tableView isEqual:self.searchDisplayController.searchResultsTableView]){
    titleLabel.text = @"";
} else {    
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
    titleLabel.text = [sectionInfo name];
}



[sectionView addSubview:titleLabel];
[titleLabel release];

return sectionView;

}

Ответы [ 5 ]

13 голосов
/ 28 февраля 2014

У нас есть лучшее решение для этой проблемы начиная с iOS6:

Существует метод делегата

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

Вы можете использовать этот метод, как этот

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

     //Set the background color of the View
     view.tintColor = [UIColor blueColor];

     // Text Color
     UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
     [header.textLabel setTextColor:[UIColor whiteColor]];

}
6 голосов
/ 07 декабря 2011

viewForHeaderInSection переопределяет метод titleForHeaderInSection.

Чтобы добавить заголовок к заголовку при использовании viewForHeaderInSection, вам необходимо добавить метку в представление заголовка раздела, например:

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

    UIView *sectionView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 728, 40)] autorelease];

    sectionView.backgroundColor = [UIColor greenColor];

    //Add label to view
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 728, 40)];
    titleLabel.text = @"title";
    [sectionView addSubview:titleLabel];
    [titleLabel release];

    return sectionView;
}  
2 голосов
/ 14 марта 2015

Реализуйте метод ниже из UITableViewDelegate, и необходим просмотр пользовательского интерфейса.

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = UITableViewHeaderFooterView()
    view.contentView.backgroundColor = UIColor(white: 0.97, alpha: 1)
    return view
}

Если вам нужно изменить нижний колонтитул, используйте аналогичный код в ... viewForFooterInSection .. method

Хотите нарисовать свой собственный шрифт, используйте аналогичные настройки:

...    
let label = UILabel(frame: CGRectMake(0, 0, CGRectGetWidth(tableView.bounds), tableView.sectionHeaderHeight))
label.font = UIFont(name: "HelveticaNeue", size: 14)!
label.text = self.tableView(tableView, titleForHeaderInSection: section)
view.contentView.addSubview(label)

view.textLabel.hidden = true
...
1 голос
/ 12 февраля 2013

Просто добавьте [titleLabel setBackgroundColor:[UIColor clearColor]];
, потому что в моем случае метка перекрывается зеленым цветом.

0 голосов
/ 14 сентября 2013

~ Лучшее решение для iPhone 3.5 и 4 экрана ~

Установите цвет фона или фоновое изображение из этого кода. Здесь вам не нужно рассчитывать высоту сечения, просто установите в xib.

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

    UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width,tableView.sectionHeaderHeight)];
    sectionView.backgroundColor = [UIColor greenColor];

    return sectionView;
}
...