UINavigationController で画面遷移する 【Objective-C xib pushViewController】
はじめに
自分用メモです。
前提
つくりたてのプロジェクト。xibファイルを使うとします。
やりたいこと
ViewController.h から NextViewController.h へ遷移させます。
手順
新規画面を追加する手順(XCode 4.6.1)
- AppDelegate.h の入っているディレクトリ上で右クリック
- Objective-C class を選択
- 以下のパラメタを入力して NextViewController.[h|m|xib] を作成
- Class: NextViewController
- Subclass of: UIViewController
- With XIB for user interface: OK
- ViewController.xib で startメソッドを呼ぶようボタンを配置
- コードを次のとおりに編集
ViewController.m
- (IBAction)start:(id)sender { NextViewController *controller = [[NextViewController alloc] initWithNibName:@"NextViewController" bundle:nil]; [self.navigationController pushViewController:controller animated:YES]; }
AppDelegate.h
#import <UIKit/UIKit.h> @class ViewController; @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @property (strong, nonatomic) UINavigationController *navigationController; @end
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { ViewController *controller = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil]; self.navigationController = [[UINavigationController alloc] initWithRootViewController:controller]; [self.navigationController setNavigationBarHidden:NO animated:NO]; [self.navigationController setToolbarHidden:YES animated:NO]; self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.window.rootViewController = self.navigationController; [self.window addSubview:self.navigationController.view]; [self.window makeKeyAndVisible]; return YES; }
蛇足
記事とは関係ないのですが、この記事を書いたのはだいぶ前で今は xibファイルで IBOutlet のコネクトはせずコードで UIButton などをつくっています。そのほうが Titanium をやってて慣れているというのと、xibファイルよりコードのほうが手が早いと感じるからです。IB で要素を削除するとxml がよくわからないことになって変にエラーが出ることもあったので。