Thursday, July 11, 2013

How to create a subview that will be a popup on large devices and full screen on small ones in iOS 6 with ARC

Universal apps are becoming more and more necessary today. They are becoming more complicated as well. At least they don't hundreds of different size screens to deal with like android.

First you should have a subview that is the size of a standard smaller screen (itouch, iphone). We will call this "SearchViewController".  You might want to use a delegate to interact with the views but we won't worry about that in this exercise.

in the SearchViewController.m;

-(void) closeView{
    //all keyboard items should have "resignFirstResponder" attached to it here just in case
    [self.view removeFromSuperview];
}

in the MainViewController.h;

#import "SearchViewController.h"

@interface MainViewController <UIPopoverControllerDelegate>{
    SearchViewController *searcher;
}

in the MainViewController.m;

-(void)OpenSearch{
    static bool isSearchOpen = FALSE;
    //open up the subview for the search function. Open up as a mini view for the ipad and a full window view for the iphone.
    if (isSearchOpen == FALSE){
        isSearchOpen = TRUE;
        if (searcher == nil){
            searcher = [[SearchViewController alloc]init];
            searcher.delegate = self;
            if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
                CGRect frame = searcher.view.frame;
                searcher.view.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-88);
            }
        }
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
            //iphone
            [self addChildViewController:searcher];
            [self.view addSubview:searcher.view];
            [searcher didMoveToParentViewController:self];
        }else{
            //ipad
            popSearch = [[UIPopoverController alloc] initWithContentViewController:searcher];
            popSearch.popoverContentSize = searcher.view.frame.size;
            popSearch.delegate = self;
            [popSearch presentPopoverFromRect:CGRectMake(self.view.frame.size.width - 5,0, 10, 10) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        }
    }else{
        isSearchOpen = FALSE;
        [self closeSearch];
    }    

}

-(void)closeSearch{
    //cancels the search and closes the search view
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
        [searcher.view removeFromSuperview];
    }else{
        [popSearch dismissPopoverAnimated:YES];
    }
    isSearchOpen = FALSE;
}

Done :)

No comments:

Post a Comment