itsame69
itsame69

Reputation: 1570

Load UIView defined in XIB into UIView

following a post presented here, I tried to load a view defined in a XIB file into a view, currently being displayed. Basically, what I want to do is to replace the middle view (see screenshot below) with a different view when the user clicks on the button.

Layout of my ViewController

This is the simple view I want to load into the middle view:

enter image description here

And this is the source code of the ViewController:

ViewController.h #import

@interface ViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIButton *loadxibButton;
@property (strong, nonatomic) IBOutlet UIView *middleView;
- (IBAction)buttonClicked:(id)sender;

@end

ViewController.m #import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}

- (IBAction)buttonClicked:(id)sender {
NSLog(@"click...");
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"NewMiddleContent" owner:self options:nil];
UIView *nibView = [nibObjects objectAtIndex:0];
self.middleView= nibView;
}
@end

When I click on the button, nothing happens, i.e. the new view will not be displayed. Can anybody please help?

Thanks a lot Christian

Upvotes: 1

Views: 8300

Answers (2)

itsame69
itsame69

Reputation: 1570

Phillip, thanks a lot!

Instead of

- (IBAction)buttonClicked:(id)sender {
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"NewMiddleContent" owner:self options:nil];
UIView *nibView = [nibObjects objectAtIndex:0];
self.middleView= nibView;
}

I now use this code:

- (IBAction)buttonClicked:(id)sender {
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"NewMiddleContent" owner:self options:nil];
UIView *nibView = [nibObjects objectAtIndex:0];

nibView.frame = CGRectMake(261, 0, 532, 748);
[[[self view] viewWithTag:2] removeFromSuperview];
[[self view] addSubview:nibView];
}

Is this want you meant, i.e. is this like "best practice"?

Bye Christian

Upvotes: 2

Phillip Mills
Phillip Mills

Reputation: 31026

Your view controller has a view property which, presumably, has three subviews (left, middle, and right). Instead of just setting a middleView property in your controller, your strategy should be to update the primary view's subviews array (removing the one that's to be replaced and inserting the new one).

Upvotes: 1

Related Questions