Trying to construct a tableview with a navigation bar at top

浪尽此生 提交于 2019-12-04 05:48:35

问题


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.



来源:https://stackoverflow.com/questions/6990915/trying-to-construct-a-tableview-with-a-navigation-bar-at-top

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!