S. Bharti S. Bharti - 1 year ago 109
Swift Question

How to show number of row in section after tapping on section header in swift?

I have a tableView which contain some

enter image description here

But i want it to show only section header and when i tap on section header it will show all employee details contining that section only.

enter image description here

Below is my code:

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


Answer Source

First add a button on your header view on that you can call a function for extending cell .

    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let titleHeader =  company[section].companyName // Also set on button
    let  headerCell = UIView(frame: CGRectMake(0   , 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

    return headerCell

Now check selected header view on buttonclicked

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

NOTE :- Here I declared selectedArray as NSMutableArray Global "tableViewObj" is your tableview object

Now proceed for final steps . make changes in your numberOfRowsInSection

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

        return 0

Try it , It'll work fine , If you have any confusion than leave comment.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download