Подтвердить что ты не робот

Как изменить цвет шрифта заголовка в сгруппированном типе UITableView?

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

Но если я изменю цвет фона таблицы на черный, названия станут неясными.

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

4b9b3361

Ответ 1

Да... Теперь он отлично работает!

Я создал метод 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

Чтобы использовать координаты по умолчанию и разделы в 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;
}

Ответ 3

Если вам просто нужно изменить цвет или шрифт заголовка, используйте 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()
    }

}

Ответ 4

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

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

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

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

Прочтите из документации Apple

Ответ 5

if ([UIDevice currentDevice].systemVersion.floatValue > 7.0) {
    [[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setTextColor:[UIColor whiteColor]];
}

Ответ 6

Swift 4.2

UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).textColor = .white