1. 程式人生 > >iOS 純程式碼設定導航欄上建立左按鈕右按鈕

iOS 純程式碼設定導航欄上建立左按鈕右按鈕

應該首先再appdelegate.m 裡面新增程式碼

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {


//1、建立視窗

self.window = [[UIWindowalloc]initWithFrame:[[UIScreenmainScreen]bounds]];

self.window.backgroundColor = [UIColorwhiteColor];

//2.建立一個導航控制器並新增子檢視

UINavigationController *nav = [[

UINavigationControlleralloc]initWithRootViewController:[ViewControllernew]];

    //nav.navigationBar.barTintColor = [UIColor redColor];

    [nav.navigationBarsetBackgroundImage:[UIImageimageNamed:@"00"]forBarMetrics:UIBarMetricsDefault];

//3.設定根檢視

self.window.rootViewController = nav;

//4、顯示視窗

    [self

.windowmakeKeyAndVisible];

returnYES;

}

其次在ViewController.m檔案裡面去定製導航欄左右按鈕,以及中間標題

- (void)viewDidLoad {

    [superviewDidLoad];

 //定製標題

//方式2

    UILabel *titleLab = [[UILabelalloc]initWithFrame:CGRectMake(0,208044)];

    titleLab.text =@"通訊錄";

    titleLab.textColor = [UIColorwhiteColor];

    titleLab.

textAlignment =NSTextAlignmentCenter;

self.navigationItem.titleView = titleLab;

//定製右按鈕

UIButton *but = [UIButtonbuttonWithType:UIButtonTypeCustom];

    but.frame =CGRectMake(0,06044);

    [but setTitle:@"下一頁"forState:UIControlStateNormal];

    [but addTarget:selfaction:@selector(Next:)forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem  *barBut = [[UIBarButtonItemalloc]initWithCustomView:but];

self.navigationItem.rightBarButtonItem = barBut;

//定製左按鈕

UIButton *but = [UIButtonbuttonWithType:UIButtonTypeCustom];

    but.frame =CGRectMake(0,06044);

    [but setTitle:@"<返回"forState:UIControlStateNormal];

    [but addTarget:selfaction:@selector(popView:)forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem  *barBut = [[UIBarButtonItemalloc]initWithCustomView:but];

self.navigationItem.leftBarButtonItem = barBut;

}

//左按鈕事件響應函式

-(IBAction)Next:(id)sender{

}

//右按鈕事件響應函式

-(IBAction)popView:(id)sender{

}