UINavigationControllerのお話(1) | 初心者がiPhoneアプリを作るブログ

初心者がiPhoneアプリを作るブログ

初心者がiPhoneアプリを作るブログです.
入門レベルですので開発初心者にも,できるだけ分かるように丁寧に説明していきます(多分).

このエントリではUINavigationControllerについて説明します.

UINavigationControllerとは

UINavigationController_example
こんなやつです.
iPhoneの画面の上にでてるバーをナビゲーションバーと呼びます.

画面を階層的に遷移させるControllerですね.

これもiPhoneアプリではよく見ますね.

さて,それではさっそくコードをのせます.
AppDelegate.h

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>{
    UINavigationController *navigationController;
}

@property (strong, nonatomic) UIWindow *window;

@end

今回は,.hファイルに変数を宣言します.
こうすることで,.mファイルの中の全ての関数の中でこの変数を使うことができます.

次に,AppDelegate.mです.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    // UIViewControllerを作成
    UIViewController *firstViewController = [[UIViewController alloc] initWithNibName:nil bundle:nil];    
    // UINavigationControllerを作成
    navigationController = [[UINavigationController alloc] initWithRootViewController:firstViewController];
    firstViewController.view = [[UIView alloc] initWithFrame:navigationController.view.frame];
    
    firstViewController.view.backgroundColor = [UIColor redColor];
    [firstViewController setTitle:@"first"];
    
    CGRect frame = firstViewController.view.frame;
    
    // UIButtonを作成
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    // 位置,サイズを設定
    button.frame = CGRectMake(frame.size.width / 2 - 50, frame.size.height / 2 - 25, 100, 50);
    // ボタンに表示する名前を設定
    [button setTitle:@"touch" forState:UIControlStateNormal];
    // ボタンを押した際の処理をする関数を設定
    [button addTarget:self action:@selector(buttonTouch:) forControlEvents:UIControlEventTouchDown];
    
    // ボタンを配置
    [firstViewController.view addSubview:button];    
    self.window.rootViewController = navigationController;
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)buttonTouch:(UIButton *)button{
    // 遷移した先のUIViewControllerを作成
    UIViewController *nextViewController = [[UIViewController alloc] initWithNibName:nil bundle:nil];
    nextViewController.view.backgroundColor = [UIColor greenColor];
    nextViewController.title = [NSString stringWithString:@"next"];
    
    // ここで遷移します
    [navigationController pushViewController:nextViewController animated:YES];
}

最近,丁寧な説明ができていない気もしますが.
気にしない!!

...さて,いきますよー!!!
まず,初めて出てくるコードはここですね
[firstViewController setTitle:@"first"];

UIViewControllerのtitleプロパティを設定することで,
ナビゲーションバーにtitleに設定した文字列を表示することができます.

CGRect frame = firstViewController.view.frame;

CGRect型とは,x座標,y座標,width,heightを格納できる型です.
なんか上手に説明できませんね笑

ここで,firstViewControllerのviewプロパティのx座標,y座標,幅,高さを取得しています.
ちなみに,x,y座標はviewの左上の座標になります.

次の記事へ

HOMEに戻る