我創建一個具有展開和折疊功能的表格視圖。我的問題是當我點擊任何部分的部分按鈕時,只有第一部分是展開。如果我再次點擊任何其他部分,只有第一部分會展開。我有一個自定義 Section 的 xib 類,我添加了一個用于擴展部分的按鈕。
這是我的代碼
我要回傳 4 個部分。
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) ->
Int {
return (sections[section].collapsed!) ? 0 : 4
}
@objc 類來處理功能
@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)
}
我的模特班
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
}
}
uj5u.com熱心網友回復:
您可以以簡單的方式展開和折疊功能。
- 首先在表格視圖資料源方法中從單元格中設定按鈕標簽
- 其次在按鈕操作方法中獲取該標簽并執行您所需的代碼。
Tableview 資料源和委托
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
}
按鈕動作
@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)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/436875.html
