UITableView get titleForHeadersInSection swift

Anupam Mishra picture Anupam Mishra · Nov 19, 2014 · Viewed 36.4k times · Source

I want to set the title of the header in the section of UITableView. What is the syntax in swift to set the title of the header in the section.

func tableView( tableView : UITableView,  titleForHeaderInSection section: Int)->String
{
    switch(section)
    {
    case 2:
        return "Title 2"
        break
    default:
        return ""
        break
    }

}

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

    var title = tableView.titleForHeaderInSection[section];
    if (title == "") {
        return 0.0;
    }
    return 20.0;
}

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

    var title = tableView.titleForHeaderInSection[section] as String
    if (title == "") {
        return UIView(frame:CGRectZero);
    }
    var headerView:UIView! = UIView (frame:CGRectMake(0, 0, self.tableView.frame.size.width, 20.0));
    headerView.backgroundColor = self.view.backgroundColor;

    return headerView;
}

Answer

HungryArthur picture HungryArthur · Apr 27, 2015

You can use the func already defined in your class i.e. :

self.tableView(tableView, titleForHeaderInSection: section)

For example, using your code:

func tableView( tableView : UITableView,  titleForHeaderInSection section: Int)->String {
   switch(section) {
     case 2:return "Title 2"

     default :return ""

   }
}

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

    var title = self.tableView(tableView, titleForHeaderInSection: section)
    if (title == "") {
        return 0.0
    }
    return 20.0
}