2

I am trying to create a custom UIView class with an associated Nib (.xib) file to help with layout and creation.

Right now, no subviews in my custom view appear, even though they exist in my nib file and are hooked up properly to my custom view class via IBOutlets.

I tried going through the following other answer: Load custom UIView with XIB from a View Controller's view using IB

and this one: How do I get a view in Interface Builder to load a custom view in another nib?

and this one: http://soulwithmobiletechnology.blogspot.com/2011/06/create-uiview-with-nib-file-in-xcode-4.html

but the method [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil] seems to call -[initWithCoder:], leading to an infinite loop.

Please let me know what other details to include to help solve this bug!

UPDATE 1: Do I need to lay out my subviews via -[layoutSubviews]? Does my nib file actually not lay it out? If so, then what is the point of the nib file?

Community
  • 1
  • 1
Ken M. Haggerty
  • 24,902
  • 5
  • 28
  • 37

1 Answers1

4

Open any of your view controllers and paste this code into your viewDidAppear method:

NSArray * allTheViewsInMyNIB = [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil]; // loading nib (might contain more than one view)
MyCustomView* problemView = allTheViewsInMyNIB[0]; // getting desired view
problemView.frame = CGRectMake(0,0,100,100); //setting the frame
[self.view addSubview:problemView]; // showing it to user

That's all you have to do, to present a view. If you want to interact with this view — you have to declare MyCustomView* problemView in your class' interface, not in the method.

Stanislav
  • 410
  • 3
  • 11
  • 1
    However, doesn't that break encapsulation? Shouldn't the only entity that cares about the nib name be the UIView itself? As per: http://blog.bignerdranch.com/129-real-iphone-crap-2-initwithnibnamebundle-is-the-designated-initializer-of-uiviewcontroller/ – Ken M. Haggerty Oct 02 '13 at 15:00
  • Also, why does this need to be in `-[viewDidAppear:]`? Why can't you instantiate in `-[viewDidLoad]` so long as you're not doing any layout? – Ken M. Haggerty Oct 02 '13 at 23:12
  • You can do it whereever you want, I've used `viewDidLoad` as an example — to help KenHaggerty get an idea of how it works. Now the code is working, he can modify it accordingly to his needs. – Stanislav Oct 03 '13 at 05:24
  • I tried using it in `-[viewDidLoad]` and I once again got an empty view. – Ken M. Haggerty Oct 03 '13 at 12:22
  • When you try to use it in `viewDidLoad` you will get nothing, because ViewController's main view is not loaded yet — it's nil. Trying to add subview to a nil-object is not an error in Obj-C, it just does nothing. You can also do it in `-(void) viewDidLayoutSubviews` — it's getting called when the main view is already inited, but not presented on screen. – Stanislav Oct 04 '13 at 17:34