iosuitapgesturerecognizeruitoolbaritem

TapGestureRecognizer on UIToolbarButton doesn't work


I have a UIToolbarButton which has a UIButton to hold the image. Now, when I click on this UIToolbarButton, I want to open another view in the current view.

My Code :

- (IBAction)btnNowPlaying:(id)sender
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(openPlaying:)];
    [self.view addGestureRecognizer:tap];
}

- (void)openPlaying:(UIGestureRecognizer *)sender
{
    NewMainViewController *vc  = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"Center"];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController * npvc = [storyboard instantiateViewControllerWithIdentifier:@"NowPlayingVC"];
    [vc.containerView addSubview:npvc.view];
}

This action, btnNowPlaying is on the UIButton.


Solution

  • It sounds like you simply want to navigate from one view controller to another. Just control-drag from your bar button item to the view controller you'd like to navigate to in your storyboard. Then, click the segue between the two view controllers and set its identifier in the Attributes inspector. After that, all you need to do is implement prepareForSegue::

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
        if ([segue.identifier isEqualToString:@"THE_IDENTIFIER_YOU_ENTERED_IN_THE_ATTRIBUTES_INSPECTOR"]) {
            if ([segue.destinationViewController isKindOfClass:[NEWViewController class]]) {
                NEWViewController *vc = (NEWViewController *)segue.destinationViewController;
                // Any preparation you need to do for next view controller
                vc.someProperty = someValue;
            }
        }
    }
    

    It's a little strange to open a new view controller inside the current view controller. Why not just segue to it?

    Another option would be to alloc-init a UIView instead of a view controller and simply addSubview:.