1

I Want to show a name and some other short informations in the sectionHeader of my Tableview.

Some of the names are very large so they don't fit, is there a way to autoresize the fontsize in the sectionHeader like in a label with:

label.adjustsFontSizeToFitWidth = true;
Fabian Gr
  • 215
  • 1
  • 12

2 Answers2

2

The easiest way would be to create a UILabel in tableView(_:viewForHeaderInSection:)

Apple Docu Discussion:

The table view uses a fixed font style for section header titles. If you want a different font style, return a custom view (for example, a UILabel object) in the delegate method tableView(_:viewForHeaderInSection:) instead.

zero3nna
  • 2,770
  • 30
  • 28
0

Simply follow the code for custom header view -

  1. Setup tableView

    tableView.estimatedSectionHeaderHeight = 80 // You can change this value accordingly
    tableView.sectionHeaderHeight = UITableViewAutomaticDimension
    
  2. Implement your custom section header and return it in the delegate method

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        switch section {
        case 0:
            return sectionHeader
        default:
            fatalError("Unreachable code")
       }
    }
    
  3. Finally, if the contents in the header section changes while the header is presented, after the change you will have to tell the tableView to redraw itself using

    func refreshTableAfterCellExpansion() {
        self.tableView.beginUpdates()
        self.tableView.setNeedsLayout()
        self.tableView.endUpdates()
    }
    
Saurabh
  • 745
  • 1
  • 9
  • 33