如何在swift中点击节标题后显示节中的行数?

前端之家收集整理的这篇文章主要介绍了如何在swift中点击节标题后显示节中的行数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个包含一些的tableView

enter image description here

但我希望它只显示标题,当我点击节标题时,它将显示仅限于该节的所有员工详细信息.

enter image description here

以下是我的代码

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return company.count
}



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

    return company[section].employees!.count
}


 func tableView(tableView: UITableView,titleForHeaderInSection section: Int) -> String? {

    if company[section].employees!.count < 1 {

        return nil
    }

    return company[section].companyName
}


 func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! EmployeeTableViewCell
    let employeeDetails =  company[indexPath.section].employees!.allObjects as! [Employees]

    cell.lblName.text = employeeDetails[indexPath.row].employeeName
    cell.lblAddress.text = String(employeeDetails[indexPath.row].address!)
    cell.lblAge.text = String(employeeDetails[indexPath.row].age!)

    return cell
}

谢谢!

解决方法

首先在标题视图上添加一个按钮,您可以调用一个函数来扩展单元格.

func tableView(tableView: UITableView,viewForHeaderInSection section: Int) -> UIView? {
    let titleHeader =  company[section].companyName // Also set on button
    let  headerCell = UIView(frame: CGRectMake(0,tableView.frame.size.width,40 ))
    headerCell.backgroundColor = UIColor.whiteColor()

    let button  = UIButton(frame: headerCell.frame)
    button.addTarget(self,action: "selectedSectionStoredButtonClicked:",forControlEvents: UIControlEvents.TouchUpInside)
  button.setTitle(titleHeader,forState: UIControlState.Normal)

    button.tag = section
    headerCell.addSubview(button)

    return headerCell
    }

现在,在buttonclicked上检查选定的标题视图

func selectedSectionStoredButtonClicked (sender : UIButton) {
    if (selectedArray.containsObject(sender.tag)){
        selectedArray.removeObject(sender.tag)
    }else{
        //selectedArray.removeAllObjects()  // Uncomment it If you don't want to show other section cell . 
        selectedArray.addObject(sender.tag)
    }
    tableViewObj.reloadData()
}

注意: – 这里我将selectedArray声明为NSMutableArray Global“tableViewObj”是你的tableview对象

现在继续进行最后的步骤.在numberOfRowsInSection中进行更改

func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
    if (selectedArray.containsObject(section)){
        return  company[section].employees!.count

    }else{
        return 0
    }
}

尝试一下,它会正常工作,如果你有任何困惑而不是发表评论.

猜你在找的Swift相关文章