awp2004
awp2004

Reputation: 41

How to switch views correctly

Im trying to use a swipe gesture to switch views. My swipe is working and being handled, but somehow the view switch doesn't function right.

Following code for the swipe handle:

-(void)handleSwipeLeft:(UISwipeGestureRecognizer *)gestureRecognizer{  
    CGPoint location = [gestureRecognizer locationInView:tableView];  
    NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:location];  
    if(indexPath){  
        userCell *cell = [tableView cellForRowAtIndexPath:indexPath]; //userCell inherits from UITableViewCell so why complain?  
        StatisticsViewController *statisticsView = [StatisticsViewController new];  
        [self.view removeFromSuperview];  
        [self.view addSubview:statisticsView.view];  
        //[self.view insertSubview:statisticsView.view atIndex:0];  
    }  
}  `

I have previously used the insertSubview: atIndex:0 before, as I have commented out. My problem is that the new view I'm trying to add is not being added. The removeFromSuperview works in the sense I get a blackscreen (hence removing the view). But I don't understand why I can't add the other view (statisticsView that I create an instance of; I am using storyboard and have a StatisticsViewController with some labels and colors just to test), I just get a blackscreen after removing the view. Btw, I am working from my rootviewcontroller named FrontPageViewController. I don't know if it would be more "right" to have a clean view controller (root) that loads in the frontpageviewcontroller and then switch it outs if I need to load another view. (But I don't see why my current approach wouldn't work). Thanks in advance

Upvotes: 0

Views: 70

Answers (1)

Guga
Guga

Reputation: 81

You main problem is because you are adding your new view to the same view you just removed. You should add it to its parent view.

About your aproach sadly I can't use comments to clarify some points but you shouldn't be doing the view switching like that.

You shouldn't be replacing the view from the controller, you should be switching between controllers.

You could do that by creating a segue with an identifier in the storyboard and adding the following to you gesture handler method:

[self performSegueWithIdentifier: @"MySegue" sender: self];

If your only intention is to replace a view in the same controller you should be creating it (just the view and not the controller) programatically and not by adding a view from one controller to another.

If you need any help with the segues I recommend you start by reading the "Add a Segue to Navigate Forward" from https://developer.apple.com/library/ios/referencelibrary/GettingStarted/RoadMapiOS/SecondTutorial.html

To manually perform a segue you will need to choose an identifier to the segue you created.

Upvotes: 1

Related Questions