How to display and hide table view cells in swift

So you want to hide one of your UITableViewCells?

Ill think the easiest way is to add some more information to your “Row Data Array”.

For example:

You have 10 Columns, and you want to hide 4 Specific Column. You have a function called “getRowData” – this returns (when no filter is selected) all 10 Rows. When you tap on a button, you could change your “getRowData” function to return only the 4 Rows you want.

With the example you showed above – you want some collapsible Lists, based on an UITableViewController.

So you have (In this example) 3 Main Categories – and if the User click on one “Title” you want to expand the list for this Category.

So you could use Sections – create a Section for each Category. Then implement something like this:

// create a main variable for your “activated Category”

var enabledCategory:Int = 0 // you could add i base value

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        let indexPath = tableView.indexPathForSelectedRow();

        enabledCategory = indexPath.row;
....

Check here which section was clicked by the user. If (for example “0” – so the first one, expand this section. So do something like this:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    if(indexPath.section == enabledCategory) {
        return rows // return rows you want to show
    }

You need also to change the count of rows in here:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {

    return 3
}

this should be (in your example) always 3.

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

This depends on your section // Category

Leave a Comment