[英]How to reload selected cell in particular section for expand/collapse in tableview Swift
我正在我的 iOS 應用程序中執行展開/折疊 tableview 單元格功能。 我有多個部分。 每個部分都有多個單元格。 默認情況下,單元格高度為 100,一旦用戶點擊單元格,我將高度增加到 200。
所以,基於布爾值,我正在改變它。 但是,在滾動表格視圖時,它正在交換部分之間的展開/折疊單元格。 就像我點擊第一部分的第一個單元格一樣,它正在擴展,但是在滾動表格視圖之后,第二部分的第一個單元格也在擴展。
我的要求是,如果用戶點擊特定單元格,則該單元格僅應展開/折疊。 用戶可以手動展開和關閉。 用戶可以展開多個單元格。
因此,我嘗試存儲 Indexpath 行和部分。
var expandedIndexSet : IndexSet = []
var expandedIndexSection : IndexSet = []
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:"cellIdentifier", for:
indexPath) as! MyTableViewCell
if expandedIndexSet.contains(indexPath.row) && expandedIndexSection.contains(indexPath.section) { // expanded true
cell.height = 200
//some other data loading here
}
else { //expanded false
cell.height = 100
}
}
@IBAction moreButtonTapped(_ sender: Any) {
if(expandedIndexSet.contains(indexPath.row)) && expandedIndexSection.contains(indexPath.section){
expandedIndexSet.remove(indexPath.row)
expandedIndexSection.remove(indexPath.section)
} else {
expandedIndexSet.insert(indexPath.row)
expandedIndexSection.insert(indexPath.section)
}
entriesTableView.beginUpdates()
entriesTableView.reloadRows(at: [indexPath], with: .none)
entriesTableView.endUpdates()
}
任何人都可以提供比這更好的方法嗎?
如果您將部分和行獨立存儲在單獨的 arrays 中,您的算法將失敗。 原因是兩者都是相互依賴的:想想三個展開的單元格 (row:1, section:1), (row:2, section:1), (row:3, section:2)
現在單元格(行:3,部分:1)會發生什么? row-array 包含值“3”,section-array 包含值“1”,因此將被視為展開。
因此,您需要將索引路徑作為一個整體存儲 - 參見示例代碼:
var expanded:[IndexPath] = []
expanded.append(IndexPath(row:1, section:1))
expanded.append(IndexPath(row:2, section:1))
expanded.append(IndexPath(row:3, section:2))
let checkPath = IndexPath(row:3, section:1)
if (expanded.contains(checkPath)) {
print ("is expanded")
} else {
print ("collapsed")
}
因此,在您的按鈕句柄中,您將執行以下操作:
@IBAction moreButtonTapped(_ sender: Any) {
if(expanded.contains(indexPath)) {
expanded.removeAll { (checkPath) -> Bool in
return checkPath == indexPath
}
} else {
expanded.append(indexPath)
}
entriesTableView.beginUpdates()
entriesTableView.reloadRows(at: [indexPath], with: .none)
entriesTableView.endUpdates()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.