uitableviewuiviewuiviewcontrollersubviews

UIView on top of UITableView


I have been developing an app in which I have a UIViewController, to which I have added a UITableView. Now I want to add a UIView on top of the tableview at a fixed position.

I tried the following code, but the UIView scrolls along with the tableView:

- (void)viewDidLoad {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(250, 100, 50, 50)];
    view.backgroundColor = [UIColor orangeColor];
    [_tableView addSubview:view];
    [_tableView bringSubviewToFront:view];
}

How can I prevent the UIView from scrolling?


Solution

  • Well, since UITableView is a subclass of UIScrollView you could try to implement something like "floating view". To do this you should make sure

    1. The floating view is always the top most view in the hierarchy
    2. The position of the floating view should be updated when the contentOffset changes (so that visually it would float on top of other content when the user is scrolling)

    You can try something like this (assuming that floatingHeaderViewCenter is the initial center of the floatingView:

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView
    {
        self.floatingHeaderView.center = CGPointMake(floatingHeaderViewCenter.x + scrollView.contentOffset.x, floatingHeaderViewCenter.y + scrollView.contentOffset.y);
        [scrollView bringSubviewToFront:floatingHeaderView];
    }
    

    Although you'd better have a view container with two subviews: your tableview and the floating view.