Kingalione Kingalione - 1 month ago 72
Swift Question

swift3 scrollToRow even when there are empty cells

I'm looking for a way to scroll to the selected cell in UITableView even if there a empty cells at bottom. My problem is that the scroll event does not scroll when there are no cells at the bottom of a table view.

As a workaround I ended up creating empty cells at the bottom and deleting those cells but I don't think that this is a good solution. So how is the way of doing this?

My code looks like this:

func scrollToSelectedCell(indexPath: IndexPath) {
self.tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.top, animated: true)
}

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

let cell = tableView.cellForRow(at: indexPath)

if (cell as? DropDownCell) != nil {
self.performSegue(withIdentifier: "showDropDownSelector", sender: cell)
} else if (cell as? PickerCell) != nil {
self.performSegue(withIdentifier: "showPickerSelector", sender: cell)
} else if let tmp_cell = cell as? TextFieldCell {
scrollToSelectedCell(indexPath: indexPath)
tmp_cell.textField.becomeFirstResponder()
}

}

Answer

You can do this more elegantly using the fact that UITableView inherits from UIScrollView. This allows you to use a combination of setting the content inset for the tableView and then changing the content offset.

Use the contentInset property to add a margin within the table view below your cells:

tableView.contentInset = UIEdgeInsetMake(top: 0, left: 0, bottom: A LARGE NUMBER, right: 0)

Then use contentOffset to set where you want the initial position of the content to be in the scrollview:

tableView.contentOffset = CGPoint(x: 0, y: SOME OTHER LARGE NUMBER TO POSITION CENTRALLY IN THE MARGIN)

You can get further information at: https://developer.apple.com/reference/uikit/uiscrollview

Hope that helps.

Comments