Search code examples
iosswiftuitableviewuipickerview

In a UITableView, how do I close the bottom border of a row after hiding the row after it?


Here's what I mean by "close the bottom border":

enter image description here

The second row is currently "hidden" (its height is set to 0). When the user clicks on the first row, the second row appears (its height is restored). If it helps, here's the code for hiding and showing the second row.

First, I have a member variable that stores whether the second row is open (it's a row with a picker view):

var referenceLengthPickerIsOpen: Bool = false

Here's how the height is determined:

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

    if indexPath.section == 0 && indexPath.row == 1 {
        return referenceLengthPickerIsOpen ? 216.0 : 0.0
    }

    return super.tableView(tableView, heightForRowAt: indexPath)
}

Here's the code for handling when the user clicks on the first row in order to show or hide the second:

override func tableView(_ tableView: UITableView,
           didSelectRowAt indexPath: IndexPath) {

    self.tableView.deselectRow(at: indexPath, animated: true)

    if indexPath.section == 0 && indexPath.row == 0 {
        referenceLengthPickerIsOpen = !referenceLengthPickerIsOpen
        tableView.beginUpdates()
        tableView.endUpdates()
    }
}

The showing and hiding part works great, with a nice animation as the second row's height changes from 0 to 216 and vice versa.

However, after hiding the second row, I'm left with the border gap shown in the image above. I know the reason: the bottom border is closed only for the last row, and it's currently hidden.

I've tried to fix this by changing the number of rows like this:

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

    if section == 0 {
        return referenceLengthPickerIsOpen ? 2 : 1;
    }

    return super.tableView(tableView, numberOfRowsInSection: section)
}

But this just crashes my app as soon as I click on the first row.


Solution

  • Go to storyboard,select cell go to Separator, custom insets and make it 0. Below is the image.

    enter image description here

    enter image description here

    Update:

    enter image description here