How to make a stationary background view in UITableView?

advertisements

I'm trying to add a view behind my grouped UITableView. Unfortunately, whenever I scroll, the background view moves as well. This happens even when I use [self.view insertSubview:backgroundView belowSubview:_tableView], or [_tableView setBackgroundView:backgroundView]. Why is this background view scrolling? Also, why does my tableView scroll, even though I have disabled scrolling? Are these related?

In app Delegate:

    History *historyController = [[History alloc] init];
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:historyController];

In History.m:

- (void)viewDidLoad {

    CGRect frame = self.view.frame;
    frame.origin.x = 0;
    frame.origin.y = 0;
    _tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView setScrollEnabled:NO];
    [_tableView setBackgroundColor:[UIColor clearColor]];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    UIView *bg = [[UIView alloc] initWithFrame:frame];
    [bg setBackgroundColor:[UIColor scrollViewTexturedBackgroundColor]];
    UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"CenterFade.png"]];
    iv.alpha = .750;
    [bg addSubview:iv];
    [iv release]; iv = nil;

    [self.view addSubview:bg];
    [self.view addSubview:_tableView];
    [bg release]; bg = nil;
    [_tableView release];

    [super viewDidLoad];
}


Try

- (void)viewDidLoad {

    CGRect frame = self.view.frame;
    frame.origin.x = 0;
    frame.origin.y = 0;

    UIView *bg = [[UIView alloc] initWithFrame:frame];
    [bg setBackgroundColor:[UIColor scrollViewTexturedBackgroundColor]];
    UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"CenterFade.png"]];
    iv.alpha = .750;
    [bg addSubview:iv];
    [iv release];
    iv = nil;

    _tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView setScrollEnabled:NO];
    [_tableView setBackgroundColor:[UIColor clearColor]];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [bg addSubview:_tableView];
    [_tableView release];
    _tableView = nil;
    [self.view addSubview:bg];
    [bg release];
    bg = nil;

    [super viewDidLoad];
}

If your controller is an UITableViewController just change it to an UIViewController<UITableViewDelegate, UITableViewDatasource> with a tableView property (It's the same)