【问题标题】:Trying to construct a tableview with a navigation bar at top尝试构建顶部带有导航栏的表格视图
【发布时间】:2011-08-09 02:54:47
【问题描述】:

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

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

我在状态栏下方看到一个黑屏,而不是一个带有表格的导航栏。

【问题讨论】:

    标签: ios uitableview uinavigationbar


    【解决方案1】:

    您需要在您的 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。

    【讨论】: