Robert
Robert

Reputation: 1589

Hide a cell in static tableview section

I'm trying to do something I would expect to be simplistic, but it's escaping me. I'm trying to show\hide the LAST cell in a tableview section. If I create an IBOutlet for the cell, and set it to hidden, the separator doesn't completely cover the bottom of the section. I've attached before and after examples. Any help would be appreciated.

enter image description here

Upvotes: 2

Views: 1836

Answers (2)

Andrew Tetlaw
Andrew Tetlaw

Reputation: 2689

The way I've done it with a static table is returned height 0 for the row you want to hide. In my case I made a set of index paths, then implemented it like this:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    guard hiddenIndexPaths.contains(indexPath as IndexPath) else {
        return super.tableView(tableView, heightForRowAt: indexPath)
    }

    return 0
}

Where hiddenIndexPaths: Set<IndexPath>, is a property on your table view controller that you manage in code. Since it's a static table you should know the index path of the row you want to hide. If you have an outlet already, you can also check that the cell at that index path is the one for your outlet and return height 0 that way. But personally I find the index path set easier.

You also need to make sure that the cell has "clips to bounds" enabled in interface builder.

Upvotes: 1

Justus Jianxing Zhang
Justus Jianxing Zhang

Reputation: 410

I think the only way you do it is set the tableview to be Dynamic Prototypes (in IB) .

Every time you try to hide/show a cell, you should callself.tableView.reloadData() .

Then implement

var hide = false

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if( section == 1 ){
        return 3 + ( hide ? 0 : 1 )
    }
    else {
        return 1
    }
}

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = self.tableView.dequeueReusableCellWithIdentifier(...) as ...
    cell.<textField>.text = ... 
    return cell
    }

Upvotes: 0

Related Questions