Best way to access subviews of views instantiated from XIB? - ios

I'm instantiating multiple clone views from a XIB, like this:
UIView *view = [[NSBundle mainBundle] loadNibNamed:#"MyNib" owner:self options:nil][0];
Then I need to access a subview (say, change a label) of every single of those views.
Connecting an element with IBOutlet wont work here (as the reference would be rewrite but the most recent view instantiated).
Here is my best shot at this so far:
for (UIView *subview in myView.subviews) {
if ([subview.restorationIdentifier isEqualToString:#"myTargetElement"]) {
// do something with the view
break;
}
}
So I'm basically iterating though subviews to find my element by restorationIdentifier. I wonder if there is a way to get a direct reference without iteration?

You can use IBOutlets. They need to be made to the custom view subclass though, not to the view controller where you add the view. Something like this works fine,
#import "ViewController.h"
#import "RDView.h"
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
RDView *view = [[NSBundle mainBundle] loadNibNamed:#"RDView" owner:self options:nil][0];
[self.view addSubview:view];
view.topLabel.text = #"Hello";
view.bottomLabel.text = #"Goodbye";
}

What's wrong with reference by outlet? I think it'll work just as fine.
It just matters on how you do the dot referencing.
Example:
UIView *view = [[NSBundle mainBundle] loadNibNamed:#"MyNib" owner:self options:nil][0];
//...
UIView *view_1 = [[NSBundle mainBundle] loadNibNamed:#"MyNib" owner:self options:nil][0];
//...
[view.someLabel setText:#"1"];
[view_1.someLabel setText:#"2"];
Anyways... alternatively, you can give the subviews a specific tag and access them via the -viewWithTag: method.
Example:
Say a UILabel in this 'MyNib' of yours has a tag 100, then you can reference it via:
[view viewWithTag:100];
//like so:
//UILabel *lblTemp = [view viewWithTag:100];
//[lblTemp setText:#"NewText"];

Related

UIView that loaded from nib files , can i set the owner to the view it self?

the most common method to init is
UIView *rootView = [[[NSBundle mainBundle] loadNibNamed:#"MyRootView" owner:self options:nil] objectAtIndex:0];
and in my case , self is refer to a view controller , but i have to set the owner to the view itself ,because there is many outlet between .m and .xib , how to do with this situations?
You should use a init method in your view.m class like:
- (id)initWithNibNamed:(NSString *)nibName{
NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:nibName owner:nil options:nil];
self = [nibContents lastObject];
if(self){
//do your code here
}
return self;
}
and call this method from viewcontroller. Connect view to view xib.
thanks stack overflow , there is already a perfect solution for this kind of problem .
https://github.com/PaulSolt/CompositeXib
the key is to call the loadNibNamed in the custom view 's implementation ,not in the controller that create the view.

Creating a reusable UIView with xib (and loading from storyboard)

OK, there are dozens of posts on StackOverflow about this, but none are particularly clear on the solution. I'd like to create a custom UIView with an accompanying xib file. The requirements are:
No separate UIViewController – a completely self-contained class
Outlets in the class to allow me to set/get properties of the view
My current approach to doing this is:
Override -(id)initWithFrame:
-(id)initWithFrame:(CGRect)frame {
self = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class])
owner:self
options:nil] objectAtIndex:0];
self.frame = frame;
return self;
}
Instantiate programmatically using -(id)initWithFrame: in my view controller
MyCustomView *myCustomView = [[MyCustomView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
[self.view insertSubview:myCustomView atIndex:0];
This works fine (although never calling [super init] and simply setting the object using the contents of the loaded nib seems a bit suspect – there is advice here to add a subview in this case which also works fine). However, I'd like to be able to instantiate the view from the storyboard also. So I can:
Place a UIView on a parent view in the storyboard
Set its custom class to MyCustomView
Override -(id)initWithCoder: – the code I've seen the most often fits a pattern such as the following:
-(id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self initializeSubviews];
}
return self;
}
-(id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self initializeSubviews];
}
return self;
}
-(void)initializeSubviews {
typeof(view) view = [[[NSBundle mainBundle]
loadNibNamed:NSStringFromClass([self class])
owner:self
options:nil] objectAtIndex:0];
[self addSubview:view];
}
Of course, this doesn't work, as whether I use the approach above, or whether I instantiate programatically, both end up recursively calling -(id)initWithCoder: upon entering -(void)initializeSubviews and loading the nib from file.
Several other SO questions deal with this such as here, here, here and here. However, none of the answers given satisfactorily fixes the problem:
A common suggestion seems to be to embed the entire class in a UIViewController, and do the nib loading there, but this seems suboptimal to me as it requires adding another file just as a wrapper
Could anyone give advice on how to resolve this problem, and get working outlets in a custom UIView with minimum fuss/no thin controller wrapper? Or is there an alternative, cleaner way of doing things with minimum boilerplate code?
Note that this QA (like many) is really just of historic interest.
Nowadays For years and years now in iOS everything's just a container view. Full tutorial here
(Indeed Apple finally added Storyboard References, some time ago now, making it far easier.)
Here's a typical storyboard with container views everywhere. Everything's a container view. It's just how you make apps.
(As a curiosity, KenC's answer shows exactly how, it used to be done to load an xib to a kind of wrapper view, since you can't really "assign to self".)
I'm adding this as a separate post to update the situation with the release of Swift. The approach described by LeoNatan works perfectly in Objective-C. However, the stricter compile time checks prevent self being assigned to when loading from the xib file in Swift.
As a result, there is no option but to add the view loaded from the xib file as a subview of the custom UIView subclass, rather than replacing self entirely. This is analogous to the second approach outlined in the original question. A rough outline of a class in Swift using this approach is as follows:
#IBDesignable // <- to optionally enable live rendering in IB
class ExampleView: UIView {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeSubviews()
}
override init(frame: CGRect) {
super.init(frame: frame)
initializeSubviews()
}
func initializeSubviews() {
// below doesn't work as returned class name is normally in project module scope
/*let viewName = NSStringFromClass(self.classForCoder)*/
let viewName = "ExampleView"
let view: UIView = NSBundle.mainBundle().loadNibNamed(viewName,
owner: self, options: nil)[0] as! UIView
self.addSubview(view)
view.frame = self.bounds
}
}
The downside of this approach is the introduction of an additional redundant layer in the view hierarchy which does not exist when using the approach outlined by LeoNatan in Objective-C. However, this could be taken as a necessary evil and a product of the fundamental way things are designed in Xcode (it still seems crazy to me that it is so difficult to link a custom UIView class with a UI layout in a way that works consistently over both storyboards and from code) – replacing self wholesale in the initializer before never seemed like a particularly interpretable way of doing things, although having essentially two view classes per view doesn't seem so great either.
Nonetheless, one happy result of this approach is that we no longer need to set the view's custom class to our class file in interface builder to ensure correct behaviour when assigning to self, and so the recursive call to init(coder aDecoder: NSCoder) when issuing loadNibNamed() is broken (by not setting the custom class in the xib file, the init(coder aDecoder: NSCoder) of plain vanilla UIView rather than our custom version will be called instead).
Even though we cannot make class customizations to the view stored in the xib directly, we are still able to link the view to our 'parent' UIView subclass using outlets/actions etc. after setting the file owner of the view to our custom class:
A video demonstrating the implementation of such a view class step by step using this approach can be found in the following video.
STEP1. Replacing self from Storyboard
Replacing self in initWithCoder: method will fail with following error.
'NSGenericException', reason: 'This coder requires that replaced objects be returned from initWithCoder:'
Instead, you can replace decoded object with awakeAfterUsingCoder: (not awakeFromNib). like:
#implementation MyCustomView
- (id)awakeAfterUsingCoder:(NSCoder *)aDecoder {
return [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class])
owner:nil
options:nil] objectAtIndex:0];
}
#end
STEP2. Preventing recursive call
Of course, this also causes recursive call problem. (storyboard decoding -> awakeAfterUsingCoder: -> loadNibNamed: -> awakeAfterUsingCoder: -> loadNibNamed: -> ...)
So you have to check current awakeAfterUsingCoder: is called in Storyboard decoding process or XIB decoding process.
You have several ways to do that:
a) Use private #property which is set in NIB only.
#interface MyCustomView : UIView
#property (assign, nonatomic) BOOL xib
#end
and set "User Defined Runtime Attributes" only in 'MyCustomView.xib'.
Pros:
None
Cons:
Simply does not work: setXib: will be called AFTER awakeAfterUsingCoder:
b) Check if self has any subviews
Normally, you have subviews in the xib, but not in the storyboard.
- (id)awakeAfterUsingCoder:(NSCoder *)aDecoder {
if(self.subviews.count > 0) {
// loading xib
return self;
}
else {
// loading storyboard
return [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class])
owner:nil
options:nil] objectAtIndex:0];
}
}
Pros:
No trick in Interface Builder.
Cons:
You cannot have subviews in your Storyboard.
c) Set a static flag during loadNibNamed: call
static BOOL _loadingXib = NO;
- (id)awakeAfterUsingCoder:(NSCoder *)aDecoder {
if(_loadingXib) {
// xib
return self;
}
else {
// storyboard
_loadingXib = YES;
typeof(self) view = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class])
owner:nil
options:nil] objectAtIndex:0];
_loadingXib = NO;
return view;
}
}
Pros:
Simple
No trick in Interface Builder.
Cons:
Not safe: static shared flag is dangerous
d) Use private subclass in XIB
For example, declare _NIB_MyCustomView as a subclass of MyCustomView.
And, use _NIB_MyCustomView instead of MyCustomView in your XIB only.
MyCustomView.h:
#interface MyCustomView : UIView
#end
MyCustomView.m:
#import "MyCustomView.h"
#implementation MyCustomView
- (id)awakeAfterUsingCoder:(NSCoder *)aDecoder {
// In Storyboard decoding path.
return [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class])
owner:nil
options:nil] objectAtIndex:0];
}
#end
#interface _NIB_MyCustomView : MyCustomView
#end
#implementation _NIB_MyCustomView
- (id)awakeAfterUsingCoder:(NSCoder *)aDecoder {
// In XIB decoding path.
// Block recursive call.
return self;
}
#end
Pros:
No explicit if in MyCustomView
Cons:
Prefixing _NIB_ trick in xib Interface Builder
relatively more codes
e) Use subclass as placeholder in Storyboard
Similar to d) but use subclass in Storyboard, original class in XIB.
Here, we declare MyCustomViewProto as a subclass of MyCustomView.
#interface MyCustomViewProto : MyCustomView
#end
#implementation MyCustomViewProto
- (id)awakeAfterUsingCoder:(NSCoder *)aDecoder {
// In storyboard decoding
// Returns MyCustomView loaded from NIB.
return [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self superclass])
owner:nil
options:nil] objectAtIndex:0];
}
#end
Pros:
Very safe
Clean; No extra code in MyCustomView.
No explicit if check same as d)
Cons:
Need to use subclass in storyboard.
I think e) is the safest and cleanest strategy. So we adopt that here.
STEP3. Copy properties
After loadNibNamed: in 'awakeAfterUsingCoder:', You have to copy several properties from self which is decoded instance f the Storyboard. frame and autolayout/autoresize properties are especially important.
- (id)awakeAfterUsingCoder:(NSCoder *)aDecoder {
typeof(self) view = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class])
owner:nil
options:nil] objectAtIndex:0];
// copy layout properities.
view.frame = self.frame;
view.autoresizingMask = self.autoresizingMask;
view.translatesAutoresizingMaskIntoConstraints = self.translatesAutoresizingMaskIntoConstraints;
// copy autolayout constraints
NSMutableArray *constraints = [NSMutableArray array];
for(NSLayoutConstraint *constraint in self.constraints) {
id firstItem = constraint.firstItem;
id secondItem = constraint.secondItem;
if(firstItem == self) firstItem = view;
if(secondItem == self) secondItem = view;
[constraints addObject:[NSLayoutConstraint constraintWithItem:firstItem
attribute:constraint.firstAttribute
relatedBy:constraint.relation
toItem:secondItem
attribute:constraint.secondAttribute
multiplier:constraint.multiplier
constant:constraint.constant]];
}
// move subviews
for(UIView *subview in self.subviews) {
[view addSubview:subview];
}
[view addConstraints:constraints];
// Copy more properties you like to expose in Storyboard.
return view;
}
FINAL SOLUTION
As you can see, this is a bit of boilerplate code. We can implement them as 'category'.
Here, I extend commonly used UIView+loadFromNib code.
#import <UIKit/UIKit.h>
#interface UIView (loadFromNib)
#end
#implementation UIView (loadFromNib)
+ (id)loadFromNib {
return [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self)
owner:nil
options:nil] objectAtIndex:0];
}
- (void)copyPropertiesFromPrototype:(UIView *)proto {
self.frame = proto.frame;
self.autoresizingMask = proto.autoresizingMask;
self.translatesAutoresizingMaskIntoConstraints = proto.translatesAutoresizingMaskIntoConstraints;
NSMutableArray *constraints = [NSMutableArray array];
for(NSLayoutConstraint *constraint in proto.constraints) {
id firstItem = constraint.firstItem;
id secondItem = constraint.secondItem;
if(firstItem == proto) firstItem = self;
if(secondItem == proto) secondItem = self;
[constraints addObject:[NSLayoutConstraint constraintWithItem:firstItem
attribute:constraint.firstAttribute
relatedBy:constraint.relation
toItem:secondItem
attribute:constraint.secondAttribute
multiplier:constraint.multiplier
constant:constraint.constant]];
}
for(UIView *subview in proto.subviews) {
[self addSubview:subview];
}
[self addConstraints:constraints];
}
Using this, you can declare MyCustomViewProto like:
#interface MyCustomViewProto : MyCustomView
#end
#implementation MyCustomViewProto
- (id)awakeAfterUsingCoder:(NSCoder *)aDecoder {
MyCustomView *view = [MyCustomView loadFromNib];
[view copyPropertiesFromPrototype:self];
// copy additional properties as you like.
return view;
}
#end
XIB:
Storyboard:
Result:
Your problem is calling loadNibNamed: from (a descendant of) initWithCoder:. loadNibNamed: internally calls initWithCoder:. If you want to override the storyboard coder, and always load your xib implementation, I suggest the following technique. Add a property to your view class, and in the xib file, set it to a predetermined value (in User Defined Runtime Attributes). Now, after calling [super initWithCoder:aDecoder]; check the value of the property. If it is the predetermined value, do not call [self initializeSubviews];.
So, something like this:
-(instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self && self._xibProperty != 666)
{
//We are in the storyboard code path. Initialize from the xib.
self = [self initializeSubviews];
//Here, you can load properties that you wish to expose to the user to set in a storyboard; e.g.:
//self.backgroundColor = [aDecoder decodeObjectOfClass:[UIColor class] forKey:#"backgroundColor"];
}
return self;
}
-(instancetype)initializeSubviews {
id view = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil] firstObject];
return view;
}
Don't forget
Two important points:
Set the File's Owner of the .xib to class name of your custom view.
Don't set the custom class name in IB for the .xib's root view.
I came to this Q&A page several times while learning to make reusable views. Forgetting the above points made me waste a lot of time trying to find out what was causing infinite recursion to happen. These points are mentioned in other answers here and elsewhere, but I just want to reemphasize them here.
My full Swift answer with steps is here.
There is a solution which is much more cleaner than the solutions above:
https://www.youtube.com/watch?v=xP7YvdlnHfA
No Runtime properties, no recursive call problem at all.
I tried it and it worked like a charm using from storyboard and from XIB with IBOutlet properties (iOS8.1, XCode6).
Good luck for coding!

Change view properties after adding it as subview

I'm creating app where i'm using pagedFlowView. I have custom view (mainDetailV) with ImageView as background and label on top. I'm using PagedFlowView delegate method to init all the views in it:
- (UIView *)flowView:(PagedFlowView *)flowView cellForPageAtIndex:(NSInteger)index{
mainDetailV = (MainDetailView *)[flowView dequeueReusableCell];
if (!mainDetailV) {
mainDetailV = [[[NSBundle mainBundle] loadNibNamed:#"MainDetailView" owner:self options:nil] lastObject];
//mainDetailV.layer.cornerRadius = 6;
mainDetailV.layer.masksToBounds = YES;
}
return mainDetailV;
}
It's adding my view 5 times in pageFlowView.
I want to trigger some action, like changing alpha of label, on tapping the imageView, but i don't really know how to do this.
My main question is how can i change properties of this view after it's added to pagedViewController?
Similar question
Access properties of subview
What is the definition of mainDetailV? It seems very strange to have this set as an Ivar
You should create mainDetailV as a local var and store it's contents in a mutable array just before you return it's value. So:
- (UIView *)flowView:(PagedFlowView *)flowView cellForPageAtIndex:(NSInteger)index{
id mainDetailV = [flowView dequeueReusableCell];
if (!mainDetailV) {
mainDetailV = [[[NSBundle mainBundle] loadNibNamed:#"MainDetailView" owner:self options:nil] lastObject];
//mainDetailV.layer.cornerRadius = 6;
mainDetailV.layer.masksToBounds = YES;
}
[usedViewControllers insertObject:mainDetailV atIndex:index];
return mainDetailV;
}
where usedViewControllers is a NSMutableArray instance variable.
Then you can use the delegate method like so:
- (void)flowView:(PagedFlowView *)flowView didTapPageAtIndex:(NSInteger)index;
{
MainDetailView *view = (MainDetailView *)[usedViewControllers objectAtIndex:index];
}
(In addition to my comment)
I have looked into PagedFlowView delegate and there is a method
- (void)flowView:(PagedFlowView *)flowView didTapPageAtIndex:(NSInteger)index;
you can use the integer index to get the cell/page from the flow view that was tapped. If you have this one you can edit its properties.
Hope this helps.

Delegate reference disappears on modal Popup

This is convoluted, so I will do my best to give as much info as possible. My main UIViewController opens a modal popup in the form of an Info screen.
here is the call from MainViewController
infoPopup = [ModalPopup modalPopupWithDelegate:self];
[infoPopup presentInView:self.view.window];
[self.view addSubview:infoPopup];
and here is the receiving method in ModalPopup
+ (id)modalPopupWithDelegate:(id <ModalPopupDelegate>)dlg {
ModalPopup *info = [[ModalPopup alloc] init];
info.delegate = dlg;
return info;
}
In ModalPopup I create a protocol with an optional method of "modalPopupFinished" and make MainViewController the delegate.
in ModalPopup I've add a UIScrollView and insert 5 UIViews into the scrollview.
I created the views all in the same XIB file
NSString *infoXib;
if (IS_IPAD)
infoXib = #"info_iPad";
else
infoXib = #"info_iPhone";
NSArray *views;
views = [[NSBundle mainBundle] loadNibNamed:infoXib owner:self options:nil];
UIView *v1 = [views objectAtIndex:0];
views = [[NSBundle mainBundle] loadNibNamed:infoXib owner:self options:nil];
UIView *v2 = [views objectAtIndex:1];
views = [[NSBundle mainBundle] loadNibNamed:infoXib owner:self options:nil];
UIView *v3 = [views objectAtIndex:2];
views = [[NSBundle mainBundle] loadNibNamed:infoXib owner:self options:nil];
UIView *v4 = [views objectAtIndex:3];
views = [[NSBundle mainBundle] loadNibNamed:infoXib owner:self options:nil];
UIView *v5 = [views objectAtIndex:4];
NSArray *pages = [NSArray arrayWithObjects:v1, v2, v3, v4, v5, nil];
[self setPagesInArray:pages];
- (void)setPagesInArray:(NSArray *)pages {
if (pages) {
int numberOfPages = pages.count;
[pageScroll setContentSize:CGSizeMake(pageScroll.frame.size.width * numberOfPages, pageHeight)];
pageControl.numberOfPages = numberOfPages;
NSUInteger i = 0;
while (i < numberOfPages) {
UIView *page = [pages objectAtIndex:i];
page.frame = CGRectMake(pageWidth * i, 0, pageWidth, pageHeight);
[pageScroll addSubview:page];
i++;
}
}
}
the Views load fine in the scrollview and I can scroll through them all as expected.
One of the views in the XIB as some buttons and I've made the view a member of the Custom Class ModalPopup. I've wired the buttons to some IBActions in ModalPopup, and they fire as expected.
In ModalPopup I create a close button that fires the delegates "modalPopupFinished" event on MainViewController.
- (void)finishCloseAnimation {
if ([_delegate respondsToSelector:#selector(modalPopupFinished)])
[_delegate modalPopupFinished];
[self removeFromSuperview];
}
No Problems everything works great...except
when I press one of the buttons from the View and goto fire a delegate method, it has lost its brain and can't remember the delegate
- (IBAction)facebook:(id)sender {
if ([_delegate respondsToSelector:#selector(sendLikeFacebook)])
[_delegate sendLikeFacebook];
}
In fact when I get into the Facebook method on ModalPopup everything is nil.
The method that I am trying to fire in MainViewController opens
[self presentViewController:composeController animated:YES completion:nil];
thus I want to open it from the main page.
It sounds to me like you have 2 instances of ModalPopup. Since you say that you wired your buttons to ModalPopup in IB, this leads me to believe you are creating an instance of ModalPopup in the xib which is distinct from the ModalPopup that you have created programmatically. The fact that the ModalPopup that is called when the button is pressed is "completely empty" is further evidence.
If this is the case, instead of programmatically creating the ModalPopup, you should get the instance from the xib, just like you get the views. I would also suspect that you already added the views to the ModalPopup in the xib which means you do not have to manually add them as well.

Loading UIView from a nib file without guesswork

Ok, here's another question.
I am creating a UIView called ProgressView that is a semi-transparent view with an activity indicator and a progress bar.
I want to be able to use this view throughout different view controllers in my app, when required.
I know of 3 different ways of doing this (but I am only interested in one):
1) Create the entire view programatically, instantiate and configure as required. No worries I get that one.
2) Create the UIView in interface builder, add the required objects and load it using a method like the below. Problem with this is that we are basically guessing that the view is the objectAtIndex:0 because nowhere in the documentation I found a reference to the order of the elements returned from the [[NSBundle mainBundle] loadNibName: function.
NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:#"yournib"
owner:self
options:nil];
UIView *myView = [nibContents objectAtIndex:0];
myView.frame = CGRectMake(0,0,300,400); //or whatever coordinates you need
[scrollview addSubview:myView];
3) Subclass UIViewController and let it manage the view as per normal. In this case I would never be actually pushing the view controller onto the stack, but only its main view:
ProgressViewController *vc = [[ProgressViewController alloc] initWithNibName:#"ProgressView" bundle:nil];
[vc.view setCenter:CGPointMake(self.view.center.x, self.view.center.y)];
[self.view addSubview:vc.view];
[vc release];
As far as I can tell, #3 is the the correct way of doing this (apart from programatically) but I am not entirely sure if it is safe to release the ProgressView's view controller whilst another controller's view is retaining its main view (gut feel says it is going to leak?)?
What do I do in terms of memory management in this case, where and when should I release the ProgressView's view controller?
Thanks in advance for your thoughts.
Cheers,
Rog
I think that your solution #3 adds unnecessary complexity by introducing a UIViewController instance just as a container for your ProgressView so that you can setup nib bindings. While I do think that it is nice to be able to work with an IBOutlet bound property rather than iterating through the nib contents you can do so without introducing a UIViewController whose behavior you neither need nor want. This should avoid your confusion around how and when to release the view controller and what, if any, side effects it might have on the responder chain or other behaviors of the loaded view.
Instead please reconsider using NSBundle and taking advantage of the power of that owner argument.
#interface ProgressViewContainer : NSObject {
}
#property (nonatomic, retain) IBOutlet ProgressView *progressView;
#end
#implementation ProgressViewContainer
#synthesize progressView = progressView;
- (void) dealloc {
[progressView release];
[super dealloc];
}
#end
#interface ProgressView : UIView {
}
+ (ProgressView *) newProgressView;
#end
#implementation ProgressView
+ (ProgressView *) newProgressView {
ProgressViewContainer *container = [[ProgressViewContainer alloc] init];
[[NSBundle mainBundle] loadNibNamed:#"ProgressView" owner:container options:nil];
ProgressView *progressView = [container.progressView retain];
[container release];
return progressView;
}
#end
Create a nib named "ProgressView" containing a ProgressView and set it's File's Owner class to ProgressViewContainer. Now you can create ProgressViews loaded from your nib.
ProgressView *progressView = [ProgressView newProgressView];
[scrollView addSubview:progressView];
[progressView release];
If you have multiple configurations of your progress view then maybe you'll want to implement a -initWithNibNamed: method on ProgressView instead of +newProgressView so you can specify which nib to use to create each ProgressView instance.
I vote for option #2. The return value from -[NSBundle loadNibNamed] is an array of the top-level objects. So as long as you have just one top level object in your nib, then the index 0 will be correct. The other views are subviews and not top level objects.
Another option of course is to do something like create a superclass for all of your view controllers that includes an outlet called something like 'progressView' and then connect your view to that outlet on file's owner in the nib. Seems like overkill for this, though.
I also prefer alternative #2. If the "0" is bothering you, you could:
Create a subclass of UIView called ProgressView
Create a nib-file called ProgressView.xib describing your progress view.
Select the topmost view in your nib, and set its Class to ProgressView in interface builder
then do
NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:#"ProgressView" owner:self options:nil];
ProgressView *progressView = nil;
for (UIView *view in nibContents) {
if ([view isKindOfClass:[ProgressView class]]) {
progressView = (ProgressView *) view;
break;
}
}
if (progressView != nil) {
//Use progressView here
}
I ended up adding a category to UIView for this:
#import "UIViewNibLoading.h"
#implementation UIView (UIViewNibLoading)
+ (id) loadNibNamed:(NSString *) nibName {
return [UIView loadNibNamed:nibName fromBundle:[NSBundle mainBundle] retainingObjectWithTag:1];
}
+ (id) loadNibNamed:(NSString *) nibName fromBundle:(NSBundle *) bundle retainingObjectWithTag:(NSUInteger) tag {
NSArray * nib = [bundle loadNibNamed:nibName owner:nil options:nil];
if(!nib) return nil;
UIView * target = nil;
for(UIView * view in nib) {
if(view.tag == tag) {
target = [view retain];
break;
}
}
if(target && [target respondsToSelector:#selector(viewDidLoad)]) {
[target performSelector:#selector(viewDidLoad)];
}
return [target autorelease];
}
#end
explanation here: http://gngrwzrd.com/blog-view-controller-less-view-loading-ios-mac.html

Resources