Nesting Custom Classes/XIB's with Interface Builder

心已入冬 提交于 2019-12-05 18:58:51

问题


I'll try to make this as short as I can.

I wrote a custom class that extends UIView with a couple of IBOutlet properties, and it has a XIB associated with it where those IBOutlets are linked to.

I then want to take that class, embed it in some other XIB (for example, a table cell), and just have it work.

It seems that when I embed that custom class in the new XIB, it does not recognize the original XIB I associated with it, so it asks for me to reset the IBOutlets to interface elements on the new XIB. This is lame.

Does anyone understand what I am trying to do and have a good approach?


回答1:


Here's how I managed to make this work:

In Interface Builder
Open your outer nib and do this:

  • Add a UIView to define the space where you want your inner nib to display.
  • Add a UIViewController object from the library, set its Nib Name property to the name of your inner nib file (without the extension).
  • Create IBOutlets for these two items in your outer view controller and wire them up. (I'll refer to them as innerView and innerViewController.)
  • Do not connect any of the IBOutlets defined in your inner view controller to anything in your outer nib file, just leave them unconnected.

In Xcode
In your outer view controller's viewDidLoad method, add these two lines:

[self.innerView addSubview:self.innerViewController.view];
self.innerViewController.view.frame = CGRectMake(0, 0, self.innerView.frame.size.width, self.innerView.frame.size.height);

If your outer nib is a custom UITableViewCell, put those lines in your awakeFromNib method instead.

Build & Run!




回答2:


I assume you're simply putting UIViews in a nib for use by a UIViewController that's purely in code. Apple calls this a detached nib file.

Follow the guide I linked to for details and example of how to get this to work.

Regarding embedding a view inside another in Interface Builder, you need to add a UIView element from the Library into the parent view, and set its class in the Inspector. Once the class of the embedded view is set, your IBOutlets should be visible.



来源:https://stackoverflow.com/questions/1750735/nesting-custom-classes-xibs-with-interface-builder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!