I Creating A Tableview With Expanding and Collapsing Feature. My issue is When I tap on section Button of any section only first section is Expand.If i click on any other section than again only first section will expand. I have A xib class for custom Section , I have added a button for expanding section.
Here's My Code
I'm returning 4 sections.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) ->
Int {
return (sections[section].collapsed!) ? 0 : 4
}
@objc Class to handle functionality
@objc func toggleCollapse(sender: UIButton) {
let section = sender.tag
let collapsed = sections[section].collapsed
sections[section].collapsed = !collapsed!
self.wareHouseTable.reloadSections(NSIndexSet(index: section) as IndexSet, with: .automatic)
}
My Model Class
struct Section {
var name: String!
var items: [String]!
var collapsed: Bool!
init(name: String, items: [String]) {
self.name = name
self.items = items
self.collapsed = true
}
}
CodePudding user response:
You can expand and collapsed functionality in simple way.
- First set button tag from cellfor row in tableview datasource method
- Second get that tag in button action method and do your required code.
Tableview DataSource & Delegate
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! UITableViewCell
cell.buttonExpand.tag = indexPath.section
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (sections[section].collapsed!) ? 0 : 4
}
Button action
@IBAction func actionExpand(_ sender:UIButton) {
let senderTag = IndexPath(item: sender.tag, section: 0) /// Return Indexpath
sections[senderTag.section].collapsed = !sections[senderTag.section].collapsed
self.wareHouseTable.reloadSections(NSIndexSet(index: senderTag.section) as IndexSet, with: .automatic)
}