iPhone programming tips #1

I have been looking at questions on forums regarding how to set outlets for UI components for different views on the iPhone (3.5” screen and 4” retina display screen) explicitly using code. I, thus, decided to share my knowledge, in how to handle this through writing a small piece of code.

Create the two views for 3.5″ and retina 4″ screens (you can select it from the file inspector) within the same xib, lets call it MyViewController.xib.

In the MyViewController.h file you need to declare the two views for which the outlets need to be set.


@property (strong, nonatomic) IBOutlet UIView *myView;

@property (strong, nonatomic) IBOutlet UIView *myView2x;

 

Define the following constant.

#define isPhone 568 ([[UIDevice currentDevice] userInterfaceIdiom]== UIUserInterfaceIdiomPhone && [UIScreen mainScreen].bounds.size.height ==568)

In the MyViewController.m file you need to add this code in the viewDidLoad function:

- (void)viewDidLoad
 

{

 

    [superviewDidLoad];

 

    /*Rest of the code */

 

    if(isPhone568)

 

    {

 

        self.view = self. myView2x;

 

        NSArray* subview= myView2x.subviews;

 

 

        for (UIView* inView in subview) {

 

            [self setSubViews:inView];

 

        }

 

    }else {

 

 

        self.view = self. myView;

 

        NSArray* subview= myView.subviews;

 

 

        for (UIView* inView in subview){

 

            [self setSubViews:inView];

 

        }

 

    }

 

}


 

The set subViews method will be something like this :

-(void)setSubViews:(UIView*)inView

{

if([inView isKindOfClass:[UIButton class]])

{

if(inView.tag==1)

{

button1 = (UIButton*)inView;

}

if(inView.tag==2)

{

button1 = (UIButton*)inView;

}

}

else if([inView isKindOfClass:[UILabel class]])

{

if(inView.tag==3)

{

label1 = (UILabel*)inView;

}

else if(inView.tag==4)

{

label2 = (UILabel*)inView;

}

}

else if([inView isKindOfClass:[UITableView class]])

{

if(inView.tag==5)

{

table = (UITableView*)inView;

}

}

}

Now set the tags for these components in the xib. Make sure you have not connected any reference outlets for the components that are used in setSubViews. Only the actions for the buttons can be connected to the file owner through the interface builder.

Now just connect the connect the two xibs' reference outlets to their respective views (myView and myView2x) and you are ready to go.

Hope this helps you.

I will try to post a video tutorial as well to make it crystal clear.

Advertisements
%d bloggers like this: