Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a custom UIView from multiple view controllers

I have created a custom UIView that I would like to use on multiple different view controllers in my iPhone application. Currently, I have copied the UIView that contains the controls from the nib file for the first view controller, pasted it into the other view controllers, and then wired up all of the actions to each view controller. This works fine, but is not the optimal way that I would like to use this custom view.

My custom view is reasonably simple, it consists of some UIButtons with labels, and tapping on these buttons fires actions that changes the contents of controls on my view controller's view.

What would be a strategy to consolidate the definition and usage of this UIView? Ideally, I would like to just reference this custom view from the nib of view controllers, and have my view controller respond to actions from this custom view.

EDIT: OK, based on J.Biard's suggestions, I have tried the following with not much luck.

I created another UIView based nib file with the contents (for now just some UIButton objects) of my reusable view and UIView subclass .m and .h files, and then set the nib File's Owner class to my newly created class name.

Then, I added most of the code from J.Biard (I changed the rect to 50,50,100,100, left out the setDelegate out for now, as I am just trying to get it working visually for now, and i found that [self.view addSubview:view] worked much better than [self addSubView:view]) to the end of the viewDidLoad method of the first view controller that is displayed when the app fires up.

And what I get now is my main view with a black square in it. Have I missed an outlet somewhere, or is there some initialization needed in initWithFrame or drawRect in the UIView subclass?

like image 863
BP. Avatar asked Feb 28 '23 15:02

BP.


1 Answers

Create your MyCustomView class and nib file.

In the nib file, set Files Owner to MyCustomView - then design your view as normal, with a top level UIView. Create an IBOutlet in MyCustomView to link to your top level UIView in your nib file.

In MyCustomView add this method:

- (BOOL) loadMyNibFile {
if (![[NSBundle mainBundle] loadNibNamed:@"MyCustomView" owner:self options:nil]) {
    return NO;
}
return YES;
}

In your view controllers you can use this custom view like so

- (void)viewDidLoad {

MyCustomView *customView = [[MyCustomView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
[customView loadMyNibFile];
[self.view addSubview:customView.view]; //customView.view is the IBOutlet you created
    [customView release];

}

You could also create a convenience class method on MyCustomView to do this if you liked.

like image 128
bandejapaisa Avatar answered Mar 28 '23 17:03

bandejapaisa