Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView get titleForHeadersInSection swift

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;
}
like image 851
Anupam Mishra Avatar asked Nov 19 '14 07:11

Anupam Mishra


Video Answer


1 Answers

Update Swift 5

Xcode - 11.4

func tableView( _ tableView : UITableView,  titleForHeaderInSection section: Int)->String? {
   switch(section) {
     case 1:return "Title of section header"
     default :return ""
   }
}

This will show header in caps lock. To make it in regular mode as you want to show it use this method along with the above mentioned:

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    let titleView = view as! UITableViewHeaderFooterView
    titleView.textLabel?.text =  "Title of section header"//titleView.textLabel?.text?.lowercased()
}
like image 191
Harjot Singh Avatar answered Oct 19 '22 13:10

Harjot Singh