I have prepared a custom UIView subclass with an associated Xib file. On the storyboard, I place a UIView and set it's class to my custom subclass. In the custom view's initWithCoder: method, I load the xib and initialize the subviews. This works great.
Now I want to use the same custom view elsewhere, but I would like the layout of my subviews to be different. I would like to make a second custom view layout in the same Xib file and load the correct one depending on which of my view controllers contains the custom view. Since all of my subviews and all of the logic are the same, just the layout is different, I'm looking for something like this:
-(id)initWithCoder:(NSCoder *)aDecoder{
if (self = [super initWithCoder:aDecoder]) {
if (self.subviews.count == 0) {
UINib *nib = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil];
UIView *subview;
if ([/*instantiating VC isKindOfClass:viewController1.class]*/) {
subview = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0];
}
else if ([/*instantiating VC isKindOfClass:viewController2.class]*/) {
subview = [[nib instantiateWithOwner:self options:nil] objectAtIndex:1];
}
subview.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
subview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self addSubview: subview];
}
}
return self;
}
Is there any way to access information about the view controller that is instantiating this custom view?
Yes there is a way, place two views and set the two view's tag different, say 10 and 20 in story board whose custom class you want to set with your UIView subclass.
Then in your UIView subclass do this:
-(id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
if (self.subviews.count == 0) {
UINib *nib = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil];
UIView *subview;
if (self.tag == 10) {
subview = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0];
}
else if (self.tag == 20) {
subview = [[nib instantiateWithOwner:self options:nil] objectAtIndex:1];
}
subview.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
subview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self addSubview: subview];
}
}
return self; }
the tag 10 view in storyboard will be replaced by your first view and the tag 20 view in storyboard will be replaced by your second view.
Build, Run and Enjoy!!!