Search code examples
objective-cmodalviewcontrollerviewdidload

Warning: Attempt to present *** whose view is not in the window hierarchy


I'm receiving this error when I am using an attached long press gesture to get a modal view to come up using the following code:

// Long press to go to settings for one
- (void)longPressOne:(UILongPressGestureRecognizer*)gesture {
       [self performSegueWithIdentifier:@"buttonOne" sender:self];
}

// Long press to go to settings for two
- (void)longPressTwo:(UILongPressGestureRecognizer*)gesture {
    [self performSegueWithIdentifier:@"buttonTwo" sender:self];
}

- (void)viewDidLoad {

    // Add gesture to buttonOne
    UILongPressGestureRecognizer *longPressOne = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressOne:)];
    [self.buttonOne addGestureRecognizer:longPressOne];


    // Add gesture to buttonTwo
    UILongPressGestureRecognizer *longPressTwo = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressTwo:)];
    [self.buttonTwo addGestureRecognizer:longPressTwo];

}

The modal segue is hitched up on the storyboard from the viewcontroller to the destination view. I know there are reports of this problem when there are multiple segues on the storyboard, but I just have the one as I can't create a segue from the button for a long press on Storyboard.

Any idea why this is happening?


Solution

  • I have fixed this by altering the code for handling the gestures, as below:

    // Long press to go to settings for one
    - (void)longPressOne:(UILongPressGestureRecognizer*)gesture {
    
            if (gesture.state == UIGestureRecognizerStateBegan)
            {
                [self performSegueWithIdentifier:@"buttonOne" sender:self];
            }
    
    }
    
    // Long press to go to settings for two
    - (void)longPressTwo:(UILongPressGestureRecognizer*)gesture {
        if (gesture.state == UIGestureRecognizerStateBegan)
        {
            [self performSegueWithIdentifier:@"buttonTwo" sender:self];
        }
    
    }
    

    This seems to fix the problem.