- 眾所周知,讓tableview具有展開與收縮功能有這樣一種方法:
- 首先創(chuàng)建兩個數(shù)組,一個數(shù)組表示展開前的數(shù)據(jù),一個數(shù)組則表示當(dāng)前節(jié)展開的子數(shù)據(jù)。
- 通過創(chuàng)建sectionHeaderView來顯示展開前的數(shù)據(jù)形式,然后再通過手勢或者button響應(yīng)事件拉伸或者收縮tableview
- 在該事件中通過一個BOOL型數(shù)據(jù),更新數(shù)據(jù)源并且reload即可完成二級列表拉伸與收縮操作。(ps:reloadRowsAtIndexPaths)
作者思量許久,若不用Section該如何讓tableview進行拉伸與收縮呢?以下是作者的思路:
- 首先創(chuàng)建一個字典,key值表示在tableview拉伸前的數(shù)據(jù),value則是一個數(shù)組表示拉伸展開的數(shù)據(jù)(一個二維數(shù)組,第一個表示展開的數(shù)據(jù),第二個表示是否已經(jīng)展開)。(注意:字典是無序的)

字典
- 接下來新建需要在tableview上顯示的數(shù)據(jù),是一個數(shù)組。在此數(shù)據(jù)上進行添加與刪除操作完成視圖的更新。

顯示的數(shù)據(jù)
- 接下來直接創(chuàng)建tableview顯示當(dāng)前的數(shù)據(jù):
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!
}
- 最關(guān)鍵的步驟來啦,點擊cell展開數(shù)據(jù)。
- 作者新建了一個全局的temp來記錄當(dāng)前展開數(shù)據(jù)的位置
var temp = 1。 - 接下來通過獲取當(dāng)前點擊cell的內(nèi)容獲取展開的數(shù)據(jù)。
let cell = tableView.cellForRow(at: indexPath)
let arr = data[(cell?.textLabel?.text)!]!
- 然后作者通過一個isExpand的Bool型內(nèi)容獲取當(dāng)前的二維數(shù)組數(shù)據(jù)是否擴展開來,擴展開來插入數(shù)據(jù),沒有擴展則刪除數(shù)據(jù)。
//判斷當(dāng)前的值
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
}
以上是作者的思路。_