Trying to construct a tableview with a navigation

2019-03-06 09:29发布

问题:

Here's the code I used. What am I missing?

- (void)loadView
{
    CGSize screen_size = [[UIScreen mainScreen] bounds].size;

    CGFloat navBarHeight = 40;

    UINavigationBar *nav = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, screen_size.width, navBarHeight)];

    UITableView *table = [[UITableView alloc] initWithFrame:CGRectMake(0, navBarHeight, screen_size.width, screen_size.height - navBarHeight) style:UITableViewStylePlain];

    table.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    table.delegate = self;
    table.dataSource = self;
    table.editing = YES;
    [table reloadData];

    [self.view addSubview:nav];
    [self.view addSubview:table];
    [nav release];
    [table release];
}

Instead of a nav bar with a table underneath, I get a black screen under the status bar.

回答1:

You need to create a containing view in your loadView method and set it as the view on your view controller:

- (void)loadView {


    CGSize screen_size = [[UIScreen mainScreen] bounds].size;

    UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0,0,screen_size.width,screen_size.height)];
    self.view = myView;

    CGFloat navBarHeight = 40;

    UINavigationBar *nav = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, screen_size.width, navBarHeight)];

    UITableView *table = [[UITableView alloc] initWithFrame:CGRectMake(0, navBarHeight, screen_size.width, screen_size.height - navBarHeight) style:UITableViewStylePlain];

    table.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    table.delegate = self;
    table.dataSource = self;
    table.editing = YES;
    [table reloadData];

    [self.view addSubview:nav];
    [self.view addSubview:table];
    [nav release];
    [table release];
    [myView release];

}

Or alternately, if you have a nib file associated with your view controller then you should be using the viewDidLoad method instead of loadView.