- 眾所周知,讓tableview具有展開與收縮功能有這樣一種方法:
- 首先創建兩個數組,一個數組表示展開前的數據,一個數組則表示當前節展開的子數據。
- 通過創建sectionHeaderView來顯示展開前的數據形式,然后再通過手勢或者button響應事件拉伸或者收縮tableview
- 在該事件中通過一個BOOL型數據,更新數據源并且reload即可完成二級列表拉伸與收縮操作。(ps:reloadRowsAtIndexPaths)
作者思量許久,若不用Section該如何讓tableview進行拉伸與收縮呢?以下是作者的思路:
- 首先創建一個字典,key值表示在tableview拉伸前的數據,value則是一個數組表示拉伸展開的數據(一個二維數組,第一個表示展開的數據,第二個表示是否已經展開)。(注意:字典是無序的)
字典
- 接下來新建需要在tableview上顯示的數據,是一個數組。在此數據上進行添加與刪除操作完成視圖的更新。
顯示的數據
- 接下來直接創建tableview顯示當前的數據:
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sectiondata.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectiondata[section]
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableview .dequeueReusableCell(withIdentifier: "cell")
if cell == nil {
cell = UITableViewCell.init(style: .default, reuseIdentifier: "cell")
}
cell?.textLabel?.text = sectiondata[indexPath.row]
return cell!
}
- 最關鍵的步驟來啦,點擊cell展開數據。
- 作者新建了一個全局的temp來記錄當前展開數據的位置
var temp = 1
。 - 接下來通過獲取當前點擊cell的內容獲取展開的數據。
let cell = tableView.cellForRow(at: indexPath)
let arr = data[(cell?.textLabel?.text)!]!
- 然后作者通過一個isExpand的Bool型內容獲取當前的二維數組數據是否擴展開來,擴展開來插入數據,沒有擴展則刪除數據。
//判斷當前的值
if isExpand {
for value in arr{
sectiondata.insert(value, at: (temp))
let index = NSIndexPath.init(row: temp, section: 0)
tableview .insertRows(at: [index as IndexPath], with: .bottom)
temp = temp + 1
}
temp = temp + 1
} else {
//此部分還沒有完善
temp = temp - 4
}
以上是作者的思路。_