尝试在顶部构建一个带有导航栏的tableview

时间:2011-08-09 02:54:47

标签: ios uitableview uinavigationbar

这是我使用的代码。我错过了什么?

- (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];
}

而不是下面有桌子的导航栏,我在状态栏下面会出现黑屏。

1 个答案:

答案 0 :(得分:2)

您需要在loadView方法中创建一个包含视图,并将其设置为视图控制器上的视图:

- (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];

}

或者,如果您有一个与视图控制器关联的nib文件,那么您应该使用viewDidLoad方法而不是loadView。