简体   繁体   中英

How to change the background color of a UITableView in the correct way?

I use code to generate UI instead of IB. I've tried setting the backgroundView to nil in the initialization of the table view, and changing the backgroundColor directly in the viewDidLoad , but both failed in changing the background color of the table view.

Finally, I set the backgroundColor in the viewWillAppear , and it works!

So, what happened between viewDidLoad and viewWillAppear on the table view? Why its background color is changed in this phrase?

Here's my code:

// in tableview's init, doesn't work
- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    self = [super initWithFrame:frame style:style];
    if (self) {
        self.backgroundView = nil;
        self.backgroundColor = [UIColor grayColor];
    }
    return self;
}

// loadView
- (void)loadView {
    _personalView = [NSBPersonalView new];
    self.tableView = _personalView;
    self.edgesForExtendedLayout = UIRectEdgeNone;
}


// in view controller's viewDidLoad, doesn't work either
- (void)viewDidLoad {
    self.tableView.backgroundColor = [UIColor grayColor];
}

// but in view controller's viewWillAppear, it works
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tableView.backgroundColor = [UIColor grayColor];
}

I think the problem is that you're not calling super loadView , super viewDidLoad . And you're not assigning self.view in loadView

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM