Как изменить цвет шрифта заголовка в сгруппированном виде UITableView? - PullRequest
40 голосов
/ 18 августа 2011

У меня есть табличное представление сгруппированного типа, и оно выглядит довольно круто.

Но, если я изменю цвет фона таблицы на черный, заголовки станут неясными.изменить цвет шрифта и его стили, чтобы я мог сделать его более читабельным?Должен ли я реализовать метод tableView:viewForHeaderInSection:?

Ответы [ 6 ]

43 голосов
/ 28 октября 2011

Чтобы использовать координаты по умолчанию и сечения в TableView, с белым шрифтом и тенью:

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
    if (sectionTitle == nil) {
        return nil;
    }

    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(20, 8, 320, 20);
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor whiteColor];
    label.shadowColor = [UIColor grayColor];
    label.shadowOffset = CGSizeMake(-1.0, 1.0);
    label.font = [UIFont boldSystemFontOfSize:16];
    label.text = sectionTitle;

    UIView *view = [[UIView alloc] init];
    [view addSubview:label];

    return view;
}
41 голосов
/ 03 декабря 2014

Если вам просто нужно изменить цвет или шрифт в заголовке, используйте tableView: willDisplayHeaderView: forSection:.Вот пример в swift:

Swift v5:

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

    if let view = view as? UITableViewHeaderFooterView {
        view.backgroundView?.backgroundColor = UIColor.blue
        view.textLabel?.backgroundColor = UIColor.clear
        view.textLabel?.textColor = UIColor.white
    }
}

Оригинал:

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

    if let view = view as? UITableViewHeaderFooterView {
        view.backgroundView?.backgroundColor = ThemeBlue
        view.textLabel.backgroundColor = UIColor.clearColor()
        view.textLabel.textColor = UIColor.whiteColor()
    }

}
22 голосов
/ 19 августа 2011

Да ... Отлично работает сейчас!

Я создал tableView:viewForHeaderInSection: метод и создал UIView

UIView *customTitleView = [ [UIView alloc] initWithFrame:CGRectMake(10, 0, 300, 44)];

Затем я создал UILabel и установил текстовые значения и цвета для метки.Затем я добавил метку к представлению

UILabel *titleLabel = [ [UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 44)];
titleLabel.text = @"<Title string here>";
titleLabel.textColor = [UIColor whiteColor];
titleLabel.backgroundColor = [UIColor clearColor];
[customTitleView addSubview:titleLabel];

Так что мой метод tableView:viewForHeaderInSection: выглядит следующим образом ...

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

    UIView *customTitleView = [ [UIView alloc] initWithFrame:CGRectMake(10, 0, 300, 44)];
    UILabel *titleLabel = [ [UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 44)];
    titleLabel.text = @"<Title string here>";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.backgroundColor = [UIColor clearColor];
    [customTitleView addSubview:titleLabel];
    return customTitleView;
}

Мы должны добавить tableView:heightForHeaderInSection: метод для предоставления некоторого пространства дляназвание.

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section 
{
    return 44; 
}
2 голосов
/ 15 июня 2015
if ([UIDevice currentDevice].systemVersion.floatValue > 7.0) {
    [[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setTextColor:[UIColor whiteColor]];
}
2 голосов
/ 18 августа 2011

Из документации Apple

В табличном представлении используется фиксированный стиль шрифта для заголовков разделов.Если вам нужен другой стиль шрифта, верните пользовательский вид (например, объект UILabel) в методе делегата tableView:viewForHeaderInSection:.

Так что используйте метод ниже и верните свой пользовательский вид (UILabel) с вашимвыбор шрифта.

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

Читать из документации Apple

0 голосов
/ 13 марта 2019

Swift 4.2

UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).textColor = .white
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...