UITableView获取titleForHeadersInSection swift

Anu*_*hra 11 uitableview swift swift-playground ios8.1

我想在UITableView部分设置标题的标题.swift中用于设置节中标题标题的语法是什么.

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;
}
Run Code Online (Sandbox Code Playgroud)

Hun*_*hur 14

您可以使用已在您的类中定义的func,即:

self.tableView(tableView,titleForHeaderInSection:section)

例如,使用您的代码:

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
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*lex 5

为了调用此方法,您必须使用 UITableViewstitleForHeaderInSection方法。该方法将提供当前节的索引,并且要求您返回一个字符串,返回的字符串将被设置为标题。

为了调用它,假设我们有一个名为的字符串数组cars

cars = ["Muscle", "Sport", "Classic"]
Run Code Online (Sandbox Code Playgroud)

然后我们可以简单地调用

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"
}
Run Code Online (Sandbox Code Playgroud)

这将按上面给出的顺序返回章节标题。