简体   繁体   中英

Hide unhide Static Table View Cells with Swift

I am trying to make a '''Static Table''' with some cells that are expandable and collapsing . I override the ''': WithAnimation:)''' which should provide me some control on the animation transition. Unfortunately, the cells returned are blank, I don't mean empty, but the cells have disappeared and their location is left blanc in the table. When I try using the '''reloadSections( )''' rather, the whole section is also returned blank. After some recherche , I start to suspect that '''reloadRowAtIndexPath(​: WithAnimation:)''' and '''reloadSections( )''' works with table associated with a data source. Am I right? If yes, how can I control animation of the cell I want to hide/unhide so that the transition is smooth? Thanks (edited)

To get a smooth animation, simply reload the tableView with

tableView.beginUpdates()
tableView.endUpdates()

this will call the heightForRowAtIndexPath automatically and render a smooth transition.

To expand on irkinosor's answer. In this example I have 1 section with 3 static rows. When tableView is initially loaded, my UISwitch is off and I only want the first row (row 0) be visible (hide rows 1,2). When the UISwitch is on, I want to show (rows 1,2). Also, I want smooth animation having the rows accordion to hide or show.

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    if indexPath.row > 0 && toggleSwitch.isOn == false {
        return 0.0  // collapsed
    }
    // expanded with row height of parent
    return super.tableView(tableView, heightForRowAt: indexPath)
}

In my switch action I initiate the tableView refresh

@IBAction func reminderSwitch(_ sender: UISwitch) {
    // to initiate smooth animation
    tableView.beginUpdates()
    tableView.endUpdates()
}

You can obviously add more logic to the heightForRowAt function if you have multiple sections and more interesting row requirements.

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