Neil
Neil

Reputation: 2058

Load XIB into a subview

I have been looking all over fo information on how to do this but have found nothing that I understand.

Basically I want to be able (from ViewController.xib) to load another XIB file on top of that view in a subview. This new subview should be manipulatable, so it can be moved around with multitouch gestures and/or swipe gestures.

I was trying to add a "view" object from ViewController, then load the other XIB into that subview object.

Hopefully someone can help. Thanks!

Upvotes: 2

Views: 6608

Answers (3)

Perfect Brains
Perfect Brains

Reputation: 33

The above code is almost right but except

UIView *newView = [[NSBundle mainBundle] loadNibNamed:@"MyNewXib" owner:self options:nil];

it should be

UIView *newView = [[[NSBundle mainBundle] loadNibNamed:@"MyNewXib" owner:self options:nil] objectAtIndex:0];

and in a view controller simply you can add

[self.view addSubview:newView];

Upvotes: 2

danh
danh

Reputation: 62686

You can define the subview in a xib by creating a xib (select File New... "user interface", "view").

You can load that view like this:

UIView *newView = [[NSBundle mainBundle] loadNibNamed:@"MyNewXib" owner:self options:nil];

That new view can now be treated like any other subview:

// assign it to a property
@property (strong, non atomic) UIView *viewFromXib;
@sythesize viewFromXib=_viewFromXib;

self.viewFromXib = newView;

// add it to your hierarchy
self.viewFromXib.frame = CGRectMake( /* this will start out 0,0 the size from the xib */ );
[self.view addSubview:self.viewFromXib];

// add gesture recognizer
UITapGestureRecognizer *tapGR =  [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
[self.viewFromXib addGestureRecognizer:tapGR];

... and so on

Upvotes: 0

Adis
Adis

Reputation: 4552

You should be able to accomplish what you want by making an instance of the other class in your ViewController, and then adding it as a subview to the current view controller.

MyOtherViewController *movc = [[MyOtherViewController alloc] init];
[self.view addSubview:movc.view];

As for handling the gestures, you could either handle them in the MyOtherViewController class, or make a container view and handle them it in your ViewController. Don't forget that they are subviews, and that any movement should be relative to their superviews.

Upvotes: 5

Related Questions