iOS用代码实现导航栏NavigationBar与跳转(Objective-C)

来源:互联网 发布:php源码分析弱类型 编辑:程序博客网 时间:2024/05/24 04:20

     当我们在使用storyboard来进行界面设计的时候,如果想要设置导航栏或者标签页(TabBar)是非常方便的。但是可能由于特殊原因,我们需要通过代码来实现导航栏,并且在导航栏的基础上进行界面跳转,我们应该怎么实现呢?该Demo我放在了  https://github.com/chenyufeng1991/JumpAndNavigationCode  中的02文件夹下 。

AppDelegate.h中实现:

#import <UIKit/UIKit.h>@class ViewController;@interface AppDelegate : UIResponder <UIApplicationDelegate>@property (strong, nonatomic) UIWindow *window;//添加导航控制器@property (strong,nonatomic) UINavigationController *naviController;//要把该界面作为第一个有导航栏的ViewController;@property (strong,nonatomic) ViewController *viewController;@end

AppDelegate.m中实现:

#import "AppDelegate.h"#import "ViewController.h"@interface AppDelegate ()@end@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    //下面这句话不能少,否则所有的导航栏和按钮都会无效;  [self.window makeKeyAndVisible];    //初始化第一个NavigationController  self.viewController = [[ViewController alloc]init];  self.naviController = [[UINavigationController alloc]initWithRootViewController:self.viewController];  [self.window addSubview:self.naviController.view];    return YES;}@end

ViewController.m中实现:

#import "ViewController.h"#import "MainViewController.h"@interface ViewController ()@property(strong,nonatomic) UIButton *button;@end@implementation ViewController- (void)viewDidLoad {  [super viewDidLoad];    self.button = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, [[UIScreen mainScreen] bounds].size.width, 20)];  [self.button setTitle:@"跳转" forState:UIControlStateNormal];  [self.button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];  [self.view addSubview:self.button];    [self.button addTarget:self action:@selector(clickMe:) forControlEvents:UIControlEventTouchUpInside];    //为导航栏增加标题;  self.title = @"首页";  }//现在我要做的是为页面增加NavagationBar,是通过代码添加的,使之在页面跳转的时候起作用;-(void)clickMe:(id)sender{    //要跳转到第二个界面;  MainViewController *mainController = [[MainViewController alloc] init];  //如果包含导航栏的话,需要使用如下方式进行界面跳转;不能使用presentViewController进行跳转;  [self.navigationController pushViewController:mainController animated:true];        }@end

我的第二个页面是一个使用nib作为界面的,对应了MainViewController,界面上没有任何控件,其中MainViewController.m实现如下:

#import "MainViewController.h"@interface MainViewController ()@property(strong,nonatomic) UIButton *backButton;@end@implementation MainViewController- (void)viewDidLoad {  [super viewDidLoad];  //设置该页面导航栏的标题;  self.title = @"第二页";      }@end

程序运行效果如下:



这样我们就可以在所有页面中增加导航栏了,是不是很方便呢?我们可以通过代码也可以实现和storyboard一样的效果,虽然有一点点麻烦。



github主页:https://github.com/chenyufeng1991  。欢迎大家访问!


1 0
原创粉丝点击