Chris Nolet Chris Nolet - 1 month ago 8
iOS Question

Add floating view (i.e. static and fixed) to UITableViewController

I'm trying to add a custom subview to a

UITableViewController
that doesn't move when the user scrolls.

Is it possible to add such a view?

I'm using a
UITableViewController
. I would switch to a
UIViewController
and add a
UITableView
, but the code relies on the UITableViewController's
refreshControl
. Adding a container view and having two controllers seems a bit much for such a simple task!

I've also tried adding the content to the
UINavigationController
view, but unfortunately it doesn't animate smoothly when the view controller appears and disappears.

Is there any way to add a fixed subview to a
UITableView
?

EDIT:

Adding a container view and having two controllers (with an embed segue) is difficult for this project, since I'm updating an older code base and there is a lot of legacy code that depends on the main controller being a
UITableViewController
. Is there any way to achieve this without an embed segue / two view controllers?

Answer

Unfortunately creating a container view for a UITableViewController inside of a UIViewController isn't feasible in this case. That is a great solution if you're early enough in development to arrange things properly.

The best solution I've found, is to transform the floating view's y position on scrollViewDidScroll as per this answer:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.header.transform = CGAffineTransformMakeTranslation(0, self.tableView.contentOffset.y);
}

I have seen other answers which modify the floating view's frame, but I think transforming is probably more appropriate.

As an interesting aside, I was able to create a floating view that 'dismisses' when the user scrolls down, but 'floats' when the user pulls to refresh by checking the table view offset before applying the transform.

Comments