UITableView - изменить цвет заголовка раздела - PullRequest
310 голосов
/ 02 мая 2009

Как мне изменить цвет заголовка раздела в UITableView?

РЕДАКТИРОВАТЬ : Ответ , предоставленный DJ-S , следует учитывать для iOS 6 и выше. Принятый ответ устарел.

Ответы [ 30 ]

11 голосов
/ 29 мая 2018

Swift 4

Чтобы изменить цвет фона , цвет текстовой метки и шрифт для представления заголовка раздела UITableView, просто переопределите willDisplayHeaderView для представления таблицы вот так:

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

Это отлично сработало для меня; надеюсь, это вам тоже поможет!

10 голосов
/ 14 декабря 2011

Вот как добавить изображение в заголовок:

- (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 голосов
/ 22 августа 2014

Для iOS8 (бета-версия) и Swift выберите нужный цвет RGB и попробуйте это:

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

}

(«Переопределение» существует, поскольку я использую UITableViewController вместо обычного UIViewController в моем проекте, но это не обязательно для изменения цвета заголовка раздела)

Текст вашего заголовка все равно будет виден. Обратите внимание, что вам нужно будет отрегулировать высоту заголовка раздела.

Удачи.

6 голосов
/ 28 июля 2016

SWIFT 2

Мне удалось успешно изменить цвет фона раздела с добавленным эффектом размытия (что действительно здорово). Чтобы легко изменить цвет фона раздела:

  1. Сначала перейдите к раскадровке и выберите просмотр таблицы
  2. Перейти к инспектору атрибутов
  3. Элемент списка
  4. Прокрутите вниз, чтобы посмотреть
  5. Изменить "Фон"

Затем для эффекта размытия добавьте код:

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 голосов
/ 02 октября 2015

Я знаю его ответ, на всякий случай, в Swift используйте следующее

    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 голосов
/ 03 ноября 2016

На основе ответа @Dj S, используя Swift 3. Это прекрасно работает на 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
}
4 голосов
/ 02 сентября 2016

iOS 8 +

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        tableView.tableHeaderView?.backgroundColor = UIColor.blue()
}
3 голосов
/ 24 января 2014

У меня есть проект с использованием статических ячеек табличного представления в iOS 7.x. willDisplayHeaderView не срабатывает. Тем не менее, этот метод работает нормально:

- (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 голосов
/ 06 февраля 2014
 -(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 голосов
/ 03 февраля 2015

Я думаю, что этот код не так уж плох.

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
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...