Question

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?

Was it helpful?

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.

OTHER TIPS

You should not add the view as a subview of the table view. Instead, the view controller view should be a container for the other views, which, in this case, is a view and a table view. Add both of these as subviews of the view controller view.

If the view(viewToBringFront) hides behind then you can make it front by adding this line:

self.viewToBringFront.layer.zPosition = MAXFLOAT;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top