Search code examples
objective-cuinavigationitempushviewcontroller

Push View Controller from IBAction


In a NavigationController I have an TabBarController. I have a custom class for TabBarController's NavigationItem, which is subclass of UINavigationItem. My NavigationItem has a TabBarButtonItem which contains an UIButton. I have defined an action for this button. My question is how can I programmatically make a push to an other view from this action? How can I get in this class the navigation controller? Or exists an other way for this?

in .h:

@interface CustomNavigationItem : UINavigationItem
{
    IBOutlet UIBarButtonItem *barbtnApply;
    IBOutlet UIButton *btnApply;
}
@property(nonatomic,retain) UIBarButtonItem *barbtnApply;
@property(nonatomic,retain) UIButton *btnApply;
-(IBAction)actionApply:(id)sender;

@end

in .m:

@implementation CustomNavigationItem

@synthesize btnApply = _btnApply;
@synthesize barbtnApply = _barbtnApply;

-(IBAction)actionApply:(id)sender
{
    btnApply = sender;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"test" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    //push to other view
}
@end

Solution

  • Maybe you should declare a delegate and call it on the button method.

    in your CustomNavigationItem.h

    @protocol CustomNavigationItemDelegate <NSObject>
    
    -(void)shouldPushViewController;
    
    @end
    
    @interface CustomNavigationItem : UINavigationItem{
          id<CustomNavigationItemDelegate> delegate;
    }
    
    @property (nonatomic, assign) id<CustomNavigationItemDelegate> delegate;
    

    in your CustomNavigationItem.m

    @implementation CustomNavigationItem
    
    @synthesize btnApply = _btnApply;
    @synthesize barbtnApply = _barbtnApply;
    @synthesize delegate;
    
     -(IBAction)actionApply:(id)sender
     {
         btnApply = sender;
         [self.delegate shouldPushViewController];
    }
    @end
    

    in your viewcontroller.m

    set the delegate

    in .h

    @interface MyViewController:UIViewController <CustomNavigationItemDelegate>
    

    in .m

     mynavigationItem.delegate = self;
    

    and implement the method

    -(void)shouldPushViewController{
        [self.navigationController pushViewController:viewControllerToPass animated:YES];
    }