ログイン



UINavigationControllerに独自デザインのボタンを設置

日曜日, 11月 13th, 2011 by

UIBarButtonItem の initWithCustomViewメソッドを使うと、独自デザインのボタンをナビゲーションバーに設置できます。以下の例では、UIImageViewに、UITapGestureRecognizerを割り当てたものを、ナビゲーションバーに表示しています。

ソースコード

以下のソースコードを、空のプロジェクトを作成し、***AppDelegateに記述すると、ナビゲーションバーに独自のアイコン”arrow.gif”が表示されます。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    UIViewController * controller = [[UIViewController alloc] init];
    [controller.view setBackgroundColor:[UIColor grayColor]];
    UINavigationController * naviViewController = [[UINavigationController alloc] initWithRootViewController:controller];
    self.window.rootViewController = naviViewController;

    UIImageView * buttonImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow.gif"]];    
    [buttonImageView addGestureRecognizer: [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(info)]];
    buttonImageView.userInteractionEnabled = YES;
    controller.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:buttonImageView];

    [self.window makeKeyAndVisible];
    return YES;
}

スクリーンショット

独自デザインのボタンがナビゲーションバーに表示されています。このボタンをタップすると、selfのinfoメソッドが実行されます。