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

Изменение размера шрифта для заголовков раздела UITableView

Может кто-нибудь, пожалуйста, проинструктирует меня о том, как проще всего изменить размер шрифта для текста в заголовке раздела UITableView?

У меня есть заголовки разделов, используя следующий метод:

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

Затем я понимаю, как успешно изменить высоту заголовка раздела с помощью этого метода:

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

У меня есть ячейки UITableView, заполненные с помощью этого метода:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

Тем не менее, я зациклился на том, как на самом деле увеличить размер шрифта - или, если на то пошло, стиль шрифта - текст заголовка раздела?

Кто-нибудь может помочь? Спасибо.

4b9b3361

Ответ 1

К сожалению, вам, возможно, придется переопределить это:

В Objective-C:

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

В Свифте:

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

Попробуйте что-то вроде этого:

В Objective-C:

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

    UILabel *myLabel = [[UILabel alloc] init];
    myLabel.frame = CGRectMake(20, 8, 320, 20);
    myLabel.font = [UIFont boldSystemFontOfSize:18];
    myLabel.text = [self tableView:tableView titleForHeaderInSection:section];

    UIView *headerView = [[UIView alloc] init];
    [headerView addSubview:myLabel];

    return headerView;
}

В Свифте:

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

    let myLabel = UILabel()
    myLabel.frame = CGRect(x: 20, y: 8, width: 320, height: 20)
    myLabel.font = UIFont.boldSystemFont(ofSize: 18)
    myLabel.text = self.tableView(tableView, titleForHeaderInSection: section)

    let headerView = UIView()
    headerView.addSubview(myLabel)

    return headerView
}

Ответ 2

Другой способ сделать это - ответить на метод UITableViewDelegate willDisplayHeaderView. Прошедшее представление фактически является экземпляром UITableViewHeaderFooterView.

Нижеприведенный пример изменяет шрифт, а также центрирует текст заголовка по вертикали и по горизонтали внутри ячейки. Обратите внимание, что вы также должны отвечать на heightForHeaderInSection, чтобы иметь какие-либо изменения в высоте заголовка, учтенные в макете представления таблицы. (То есть, если вы решите изменить высоту заголовка в этом методе willDisplayHeaderView.)

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

Objective-C

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

    header.textLabel.textColor = [UIColor redColor];
    header.textLabel.font = [UIFont boldSystemFontOfSize:18];
    CGRect headerFrame = header.frame;
    header.textLabel.frame = headerFrame;
    header.textLabel.textAlignment = NSTextAlignmentCenter;
}

Swift 1.2

(Примечание: если ваш контроллер просмотра является потомком UITableViewController, это нужно объявить как override func.)

override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) 
{
    let header:UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView

    header.textLabel.textColor = UIColor.redColor()
    header.textLabel.font = UIFont.boldSystemFontOfSize(18)
    header.textLabel.frame = header.frame
    header.textLabel.textAlignment = NSTextAlignment.Center
}

Swift 3.0

Этот код также гарантирует, что приложение не сработает, если ваш заголовок представляет собой нечто иное, чем UITableViewHeaderFooterView:

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    guard let header = view as? UITableViewHeaderFooterView else { return }
    header.textLabel?.textColor = UIColor.red
    header.textLabel?.font = UIFont.boldSystemFont(ofSize: 18)
    header.textLabel?.frame = header.frame
    header.textLabel?.textAlignment = .center
}

Ответ 3

В то время как ответ mosca1337 является правильным решением, будьте осторожны с этим методом. Для заголовка с текстом длиной более одной строки вам нужно будет выполнить вычисления высоты заголовка в tableView:heightForHeaderInSection:, что может быть громоздким.

Наиболее предпочтительным методом является использование API внешнего вида:

[[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setFont:[UIFont boldSystemFontOfSize:28]];

Это изменит шрифт, оставив таблицу для управления самой высотой.

Для оптимальных результатов подклассируйте представление таблицы и добавьте его в цепочку сдерживания (в appearanceWhenContainedIn:), чтобы убедиться, что шрифт изменен только для определенных видов таблицы.

Ответ 4

Для iOS 7 я использую это,


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

    header.textLabel.font = [UIFont boldSystemFontOfSize:10.0f];
    header.textLabel.textColor = [UIColor orangeColor];
}

Вот версия Swift 3.0 с изменением размера заголовка

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    if let header = view as? UITableViewHeaderFooterView {
        header.textLabel!.font = UIFont.systemFont(ofSize: 24.0)
        header.textLabel!.textColor = UIColor.orange          
    }
}

Ответ 5

Swift 3:

Самый простой способ настроить только размер:

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

    let header = view as! UITableViewHeaderFooterView

    if let textlabel = header.textLabel {
        textlabel.font = textlabel.font.withSize(15)
    }
}

Ответ 6

Swift 2.0:

  • Замените заголовок раздела по умолчанию полностью настраиваемым UILabel.

Внедрить viewForHeaderInSection, например:

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

    let sectionTitle: String = self.tableView(tableView, titleForHeaderInSection: section)!
    if sectionTitle == "" {
      return nil
    }

    let title: UILabel = UILabel()

    title.text = sectionTitle
    title.textColor = UIColor(red: 0.0, green: 0.54, blue: 0.0, alpha: 0.8)
    title.backgroundColor = UIColor.clearColor()
    title.font = UIFont.boldSystemFontOfSize(15)

    return title
  }
  1. Изменить заголовок по умолчанию (сохраняется по умолчанию).

Внедрение willDisplayHeaderView, например:

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

    if let view = view as? UITableViewHeaderFooterView {
      view.backgroundView?.backgroundColor = UIColor.blueColor()
      view.textLabel!.backgroundColor = UIColor.clearColor()
      view.textLabel!.textColor = UIColor.whiteColor()
      view.textLabel!.font = UIFont.boldSystemFontOfSize(15)
    }
  }

Помните: если вы используете статические ячейки, заголовок первого раздела заполняется выше других заголовков разделов из-за вершины UITableView; исправить это:

Внедрите heightForHeaderInSection, например:

  override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

    return 30.0 // Or whatever height you want!
  }

Ответ 7

С помощью этого метода вы можете установить размер шрифта, стиль шрифта и фон заголовка. есть 2 метода для этого

Первый метод

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
        UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
        header.backgroundView.backgroundColor = [UIColor darkGrayColor];
        header.textLabel.font=[UIFont fontWithName:@"Open Sans-Regular" size:12];
        [header.textLabel setTextColor:[UIColor whiteColor]];
    }

Второй метод

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 30)];
//    myLabel.frame = CGRectMake(20, 8, 320, 20);
    myLabel.font = [UIFont fontWithName:@"Open Sans-Regular" size:12];
    myLabel.text = [NSString stringWithFormat:@"   %@",[self tableView:FilterSearchTable titleForHeaderInSection:section]];

    myLabel.backgroundColor=[UIColor blueColor];
    myLabel.textColor=[UIColor whiteColor];
    UIView *headerView = [[UIView alloc] init];
    [headerView addSubview:myLabel];
    return headerView;
}

Ответ 8

Swift 4 версия Лео Натан ответ

UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = UIFont.boldSystemFont(ofSize: 28)

Если вы хотите установить собственный шрифт, вы можете использовать

if let font = UIFont(name: "font-name", size: 12) {
    UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = font
}

Ответ 9

Swift 2:

Как запросил OP, только отрегулируйте размер, не устанавливая его как жирный шрифт системы или что-то еще:

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        if let headerView = view as? UITableViewHeaderFooterView, textLabel = headerView.textLabel {

            let newSize = CGFloat(16)
            let fontName = textLabel.font.fontName
            textLabel.font = UIFont(name: fontName, size: newSize)
        }
    }