简体   繁体   中英

UITableView reload section while viewing

After pressing a button on one of my custom TableViewCells I would like to hide/unhide an image on other custom TableViewCells. My cells are ordered in sections.

The changes take effect if I press the button, switch to another view and then come back to my TableView. I would like the changes to appear right away without needing to switch views.

My code:

        let otherCellIndexPath = IndexPath(item: 0, section: 0)
        let otherCell = tableView.cellForRow(at: oldIndexPath) as! CustomTableViewCell
        otherCell.hideImage()

        let currentCell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell
        currentCell.showImage()

        tableView.beginUpdates()
        tableView.reloadSections([otherCellIndexPath,indexPath], with: .none)
        tableView.endUpdates()

What am I missing? (using Xcode 8 b6, Swift 3)

I avoid calling cellForRow in my code. Instead I maintain a dictionary for state of each cell like

var dictSection0 = [["ImageName" : "SampleImageSection0Row0","hidden":true],["ImageName" : "SampleImageSection0Row1","hidden":false]]

var dictSection1 = [["ImageName" : "SampleImageSection1Row0","hidden":true],["ImageName" : "SampleImageSection1Row1","hidden":false]]
var tableDataModel = [dictSection0,dictSection1]

On the button tap I would modify the dictionary. In the above case setting hidden to true for row 1 of section 0

var rowDict = tableDataModel[0][1]
rowDict["hidden"] = true

and then reload the entire table (or a part of it like you are doing) to reflect the changes.

in the cellForRow atIndexPath method this dictionary is used to show/hide the image in the cell.

var rowData = tableDataModel[indexPath.section][indexPath.row]
let tableCell = tableView.dequeueReusableCellWithIdentifier("customCell", forIndexPath: indexPath)
tableCell.imageView.hidden = rowDict["hidden"]

@Manali建议执行的操作,调用tableView.reloadSections触发对cellForRowAtIndexPath的一系列调用,在该方法内部,出队的单元格可能与通过调用cellForRow得到的对象不完全相同,正确的方法是存储有关隐藏/取消隐藏,以及显示/隐藏cellForRowAtIndexPath内部的图像

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM