sendSubviewToBack on UITableView not working properly in iOS 11

Viewed 1034

I have an UITableViewController to which I successfully applied in the past a gradient background, by sending the newly added subview to back:

//performed on viewDidLoad
UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1.5*280, 1.5*SCREEN_HEIGHT)];
bgView.backgroundColor = [UIColor yellowColor];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = bgView.bounds;
gradient.startPoint = CGPointMake(0, 0);
gradient.endPoint = CGPointMake(1, 1);
UIColor *topColor = UIColorFromRGB(0x229f80);
UIColor *bottomColor = UIColorFromRGB(0x621ad9);
gradient.colors = [NSArray arrayWithObjects:(id)[topColor CGColor], (id)[bottomColor CGColor], nil];
[bgView.layer insertSublayer:gradient atIndex:0];
[self.view addSubview:bgView];
[self.view sendSubviewToBack:bgView];
bgView = nil;

However, this no longer works in iOS 11 and the bgView is actually placed on top of all the cells.

enter image description here

Anyone knows how I can fix this? Or maybe I was doing it wrong all the time?

4 Answers

If your cells are transparent then you can try self.tableView.backgroundView = bgView;

If you don't need the background view to be scrolling together with the table view, you can use

self.tableView.backgroundView = bgView;

If you need the background view to be scrolling, change layer's zPosition to a negative value to make it work in iOS 11:

[self.view insertSubview:bgView atIndex:0];
bgView.userInteractionEnabled = NO;
bgView.layer.zPosition = -1;

Another way to fix it is to call [self.view sendSubviewToBack:bgView]; in tableView:willDisplayCell:forRowAtIndexPath:

It works for not transparent cells also.

it appears that addSubview(UIView) sendSubview(toBack: UIView) no longer works for UITableViewControllers in iOS11. So I swap to this:

// in ViewDidLoad
// set the backgroundImage
    let backgroundImage = UIImageView(frame: self.view.bounds)
    backgroundImage.image = UIImage(named: "background.png")
//        self.view.addSubview(backgroundImage) // NO LONGER WORKS
//        self.view.sendSubview(toBack: backgroundImage) // NO LONGER WORKS
    self.tableView.backgroundView = backgroundImage
Related