以编程方式在UIViewController中添加UINavigationController

6

我目前设置了如下的视图:

@interface BlogViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
    UITableView *mainTableView;
}

@property (nonatomic, retain) UITableView *mainTableView;

正如您所看到的,它里面有一个UITableView,我会将所有数据加载到其中。然而,当我调用以下函数时:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SingleBlogViewController *viewController = [[SingleBlogViewController alloc] init];
    [self.navigationController pushViewController:viewController animated:YES];
    //[self presentModalViewController:viewController animated:YES];
    [viewController release];
}

什么也没发生。由于某些原因,我的UIViewController中的UITableView没有推动视图。这是因为它不是UITableViewController吗?我尝试将其更改为UITableViewController,但仍然无法工作。

我在这里漏掉了什么吗?


1
BlogViewController本身是如何显示的?它是被推送出来的还是作为导航控制器的根视图控制器呢? - user467105
这是一个使用presentModalViewController:显示的模态视图。 - joshholat
你是如何将你的UIViewController添加到程序中的?通过UINavigationController吗? - jmont
2个回答

26

我发现这篇博客文章的前几部分对于展示如何在代码中创建和使用UINavigationController非常有用,而不需要使用Interface Builder。

以下是一些我希望文档和教程能够强调的内容:

  • 当你创建UINavigationController时,你会免费获得一个UIView和UINavigationBar(即无需单独添加它们并确定如何将它们连接在一起)。

  • 你可以将myUINavigationController.view属性作为“主”视图添加,并将UIViewController推入/弹出UINavigationController,它们会自动显示在myUINavigationController.view UIView中。

  • 当你将一个UIViewController推入UINavigationController时,UIViewController.navigationController会被填充。如果你还没有将视图推入导航控制器中,则该属性应该为空。

  • 编程方式添加按钮到UINavigationBar的时间/位置不是在构造UINavigationController时和地点,而是通过单个UIViewController在推入UINavigationController时加载时。

  • 我只需要在第一个被推入UINavigationControllerUIViewControllerviewDidLoad方法中添加一个“完成”按钮到UINavigationControllerUINavigationBar上。任何我在其之上推入的UIViewController都会自动具有一个“返回”按钮,以导航到被覆盖的UIViewController

  • 如果你在将 UIViewController 放入 UINavigationController 的堆栈之前设置了其 title 属性,则 UINavigationBar 的标题将是你的视图的标题。此外,任何 "返回" 按钮都会自动命名为你返回到的视图,而不是通用地显示 "返回"。


  • 抱歉打扰了,你提供的博客文章已经失效了,有没有其他地方可以找到它?谢谢。 - armnotstrong
    @armnotstrong 试试这个 https://web.archive.org/web/20120501094236/http://theolternative.wordpress.com:80/2009/04/27/iphone-dev-tips-navigation-and-tap-bar-controller/ - David Blevins

    -3
    请访问 "如何以编程方式添加UINavigationController"。
    请访问上面的链接并获取有关UINavigationController的所有信息。
    UINavigationController是UIViewController的子类,但与UIViewController不同,它通常不适合您进行子类化。这是因为导航控制器本身很少定制除了导航栏的外观之外的内容。可以相对轻松地在代码中或XIB文件中创建UINavigationController的实例。

    2
    我认为问题是如何在UIViewController中创建UINavigationController,上面的链接只展示了如何在AppDelegate主类中创建UINavigationController。 - C0D3

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接