UITableView get titleForHeadersInSection swift

霸气de小男生 提交于 2019-12-05 01:15:13

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
}

In order to call this method you must use the UITableViews titleForHeaderInSection method. This method will provide the index for the current section and you are required to return a String, the returned String will be set as the header.

In order to invoke this, lets assume we have an array of Strings called cars

cars = ["Muscle", "Sport", "Classic"]

We can then simply call

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? 
{
    // Ensure that this is a safe cast
    if let carsArray = cars as? [String]
    {
        return carsArray[section]
    }

    // This should never happen, but is a fail safe
    return "unknown"
}

This will return section titles in the order given above.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!