iosswiftuitableviewscrolluicontainerview

How to get contents of container view to scroll in sync with parent tableview in Swift?


I have a table view controller which contains a view and below that, 2 container views. Each container view containing individual tableviews with some data (see diagram).

A segment control is used to switch between which of the container views are visible.

The content within the container views extend beyond the height of the main screen.

Currently the parent tableview controller is scrolling independently to the table views within the container views which is expected.

How can I sync the container views and parent tableview to scroll together?

Current hierarchy is shown in the diagram below:

Current view controller hierarchy


Solution

  • Usually having this kind of UX/UI is not a good idea. I personally hate this UX.
    But to answer your question, you could observe for the contentOffset property of both child tableViews using KVO and update the parent tableView's contentOffset accordingly by doing the appropriate calculations.

    Btw, you could use a regular UIViewController and UIScrollView as a containerView instead of the UITableViewController


    The ideal approach for me is having a SINGLE tableView, and loading all the content dynamically. F.e. you could have the segment control (and all static data) in the tableViewHeaderView, and depending on which tab is selected you could update the content of the tableView accordingly by switching the array of the first tab's datasource to the second tab's, and vice-versa. Even if the UI of the cells differs for both tabs, you could dequeue two different cells depending on the selected tab.