微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在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
    }
}

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐