Swift按单元格按钮单击展开/折叠单元格

时间:2017-12-12 06:18:50

标签: ios swift uitableview collapse expand

我有一个带有一个UILabel和UIButton的自定义单元格。我想要另一个细胞 通过点击父单元格的按钮展开/折叠,如果点击父单元格UIButton然后子单元格应该展开/折叠,我们还需要父和子单元格委托的不同操作。

谢谢。

1 个答案:

答案 0 :(得分:0)

你可以这样做,并相应地修改它。不要将Button和label作为单元格添加为节标题。

var data: [[String:Any]]!

override func viewDidLoad() {
    super.viewDidLoad()
    data = [["sectionHeader": "section1","isCollapsed":true,"items":["cell1","cell2","cell3","cell4","cell5"]],["sectionHeader": "section2","isCollapsed":true,"items":["cell1","cell2","cell3","cell4","cell5"]],["sectionHeader": "section3","isCollapsed":true,"items":["cell1","cell2","cell3","cell4","cell5"]],["sectionHeader": "section4","isCollapsed":true,"items":["cell1","cell2","cell3","cell4","cell5"]]]
    // Do any additional setup after loading the view, typically from a nib.
    tableView.reloadData()
}

func numberOfSections(in tableView: UITableView) -> Int {
    return data.count
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 40
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = UIView.init(frame: CGRect.init(x: 0, y: 0, width: tableView.frame.size.width, height: 40))
    let label = UILabel.init(frame: CGRect.init(x: 16, y: 0, width: 100, height: 40))
    label.text = data[section]["sectionHeader"] as? String
    view.addSubview(label)

    let button = UIButton.init(frame: CGRect.init(x: tableView.frame.size.width - 60, y: 0, width: 50, height: 40))
    button.setTitle("Data", for: .normal)
    button.setTitleColor(UIColor.blue, for: .normal)
    button.addTarget(self, action: #selector(self.sectionButtonTapped(button:)), for: .touchUpInside)
    button.tag = section
    view.addSubview(button)
    return view
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let isCollapsed = data[section]["isCollapsed"] as! Bool
    let item = data[section]["items"] as! [String]
    return isCollapsed ? 0 : item.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let item = data[indexPath.section]["items"] as! [String]
    cell.textLabel?.text = item[indexPath.row]
    return cell
}

@objc func sectionButtonTapped(button: UIButton) {
    let section = button.tag
    let isCollapsed = data[section]["isCollapsed"] as! Bool
    if isCollapsed {
        data[section]["isCollapsed"] = false
    }
    else {
        data[section]["isCollapsed"] = true

    }
    self.tableView.reloadData()
}

输出:

https://media.giphy.com/media/l3mZhZfzXKD0Ugecw/giphy.gif

相关问题