我试图在UIView程序中添加一个UINavigationBar并取得如此成功,并且无法弄清楚.我正在尝试将其添加到我的UIView子类中,当我运行我的应用程序时,它根本不显示.
这是我的代码:
UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0,self.frame.size.width,headerHeight)]; [navBar setBackgroundColor:[UIColor blueColor]]; [self addSubview:navBar]; UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] initWithTitle:@"done" style:UIBarButtonItemStylePlain target:self action:@selector(done:)]; UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:@"categories"]; [navItem setRightBarButtonItem:doneItem animated:YES]; [navBar setItems:[NSArray arrayWithObject:navItem] animated:YES];
解决方法
如果您从第一个视图使用导航控制器,我建议您在Appdelegate.m中
UIViewController *viewController = [[MenuViewController alloc] initWithNibName:@"FirstViewController" bundle:nil]; UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController]; self.window.rootViewController=navController;
但是如果您有一个视图来呈现您想要的导航栏的新视图,则使用此视图显示新视图:
UIViewController *viewController = [[MenuViewController alloc] initWithNibName:@"MenuViewController" bundle:nil]; UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController]; [self presentViewController:navigationcontroller animated:YES completion:nil];
那么您可以在第二个视图中添加navBarButton,如下所示:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { UIBarButtonItem *btnAdd = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(btnAddGroupPressed)]; self.navigationItem.rightBarButtonItem=btnAdd; } return self; }