Nitish
Nitish

Reputation: 14113

Common views in viewControllers - Code re-usability

I have few common views in most of my viewControllers. What I noticed is that I can reuse single code for all viewControllers which is absolutely wise. For this I decided to create a class Utils which has static methods like

+(void)createCommonViews:(float)yAxis:(NSString*)text;  

In my case common views are three labels and two images.

Problem : I am not able to add these views from Utils. I am wondering how can I send self as a parameter so that I may add the views from Utils. It may be wrong to add views outside the viewController. In that case what can be the solution? Taking all these views in a UIView, setting return type of Utils method as UIView and then adding UIView to viewController (after calling method from viewController) might solve my problem. But what I am looking for is some other solution.

Upvotes: 1

Views: 167

Answers (3)

amleszk
amleszk

Reputation: 6290

Create a viewController that acts as a parent view for all your common stuff, call it CommonViewController then implement this in all the viewcontrollers you want it to appear

-(void) viewDidLoad 
{
   [self.view addSubView:[[CommonViewController alloc] initWithRect:..];
}

Or alternatively using xib files

Upvotes: 1

QED
QED

Reputation: 9913

The method you're attempting is to have your view object as a singleton. This is uncommon at best, at worst a crash waiting to happen. Better design is for each of your view controller classes to have its own instance of your custom view, like so:

@interface MyCommonView : UIView

// ...

@end



@interface MyViewController_A : UIViewController {
   MyCommonView *commonView;
}

@property (strong, nonatomic) IBOutlet MyCommonView *commonView;

@end



// Meanwhile somewhere else...



@interface MyViewController_B : UIViewController {
   MyCommonView *commonView;
}

@property (strong, nonatomic) IBOutlet MyCommonView *commonView;

@end

Upvotes: 1

Adrian Ancuta
Adrian Ancuta

Reputation: 1036

+(void) createCommonViews:(float)yAxis withText:(NSString*) text toTarget:(UIViewController*) target
{
//create views
    [target addSuview:view];
}

But I think returning a Uiview and then adding it in the UIViewController afterwards, is a far better solution.

Upvotes: 1

Related Questions