Sakkeer Hussain
Sakkeer Hussain

Reputation: 459

How to add a view to all of my view controllers from base UIViewController programmatically in iOS

I have four view controllers in my app, all are extended from a common UIViewController class. I wanted to add a view commonly for all of my view controllers at bottom.

Now I am adding that view in viewDidLoad method of base view controller like this

UIView *contentView = [[UIView alloc]initWithFrame:self.view.frame];
UIView *wrapperView = [[UIView alloc]initWithFrame:self.view.frame];
UIView *commonView = [[UIView alloc]init];
commonView = <common view>;
[contentView setTranslatesAutoresizingMaskIntoConstraints:NO];
[wrapperView setTranslatesAutoresizingMaskIntoConstraints:NO];


wrapperView.backgroundColor = [UIColor blueColor];
contentView.backgroundColor = [UIColor greenColor];

contentView = self.view;
[wrapperView addSubview:contentView];
[wrapperView addSubview:commonView];
self.view = wrapperView;

This is working fine when I turned off autolayout of the particular storyboard. But when I enable autolayout I getting green colour on screen(contentView).

There are 9 autolayout constraints for view controller before the above code running and after above code snippet there is no constraint for self.view

Is there any way to add autolayout constraints of self.view back?

Upvotes: 0

Views: 167

Answers (1)

Casey
Casey

Reputation: 6691

remove this line:

contentView = self.view;

that line is causing the initialization of contentView (the first line of your code) to essentially be a no-op.

why are you attempting to reset the entire layout when adding the view? it seems like you could just initialize commonView and add it directly to self.view:

UIView *commonView = [[UIView alloc] init];
commonView = <common view>;
[self.view addSubview:commonView];

Upvotes: 0

Related Questions