113

I have been searching everywhere and nothing so far has worked for me.

Basically I want to have a .xib file called rootView.xib and inside it I want to have a UIView (lets call it containerView) that takes up only half of the screen (so there would be the regular view and a new view). Then I want a different .xib file called firstView.xib and load it inside of containerView. So I can have a bunch of stuff on firstView.xib and a bunch of different stuff in rootView.xib and load my firstView.xib inside of containerView in rootView.xib but since it only takes up half of the screen you would still see the stuff on rootView.xib

Cristik
  • 30,989
  • 25
  • 91
  • 127
Matt
  • 2,920
  • 6
  • 23
  • 33
  • 2
    Note, this questin is archaic. For many years now, simply use container views [tutorial](http://stackoverflow.com/questions/23399061/objective-c-how-to-add-a-subview-that-has-its-own-uiviewcontroller/23403979#23403979) – Fattie Jul 07 '16 at 01:39

7 Answers7

184

To get an object from a xib file programatically you can use: [[NSBundle mainBundle] loadNibNamed:@"MyXibName" owner:self options:nil] which returns an array of the top level objects in the xib.

So, you could do something like this:

UIView *rootView = [[[NSBundle mainBundle] loadNibNamed:@"MyRootView" owner:self options:nil] objectAtIndex:0];
UIView *containerView = [[[NSBundle mainBundle] loadNibNamed:@"MyContainerView" owner:self options:nil] lastObject];
[rootView addSubview:containerView];
[self.view addSubview:rootView];
chown
  • 51,908
  • 16
  • 134
  • 170
  • @PaulSolt sir i have a query related to this queston. i want to open subview of xib as slide menu. When i click on menu button from the view controller only subview(which is half screen of xib) should be slide. please help if it possible. – sandeep tomar May 06 '16 at 12:42
  • It not works with `thisView.alpha = 0` , `thisView.superview`(shows nil) – Jack Dec 27 '17 at 05:23
23

I created a sample project on github to load a UIView from a .xib file inside another .xib file. Or you can do it programmatically.

This is good for little widgets you want to reuse on different UIViewController objects.

  1. New Approach: https://github.com/PaulSolt/CustomUIView
  2. Original Approach: https://github.com/PaulSolt/CompositeXib

Load a Custom UIView from .xib file

Paul Solt
  • 8,375
  • 5
  • 41
  • 46
  • Great lib, works great ! Are you still using it yourself ? :) – AnthoPak Mar 15 '19 at 15:26
  • I use this loading technique with a Storyboard and XIB file for a custom view in my http://BrewCoffeeApp.com when the coffee recipe has started. – Paul Solt Mar 18 '19 at 21:43
21

[Swift Implementation]

Universal way of loading view from xib:

Example:

let myView = Bundle.loadView(fromNib: "MyView", withType: MyView.self)

Implementation:

extension Bundle {

    static func loadView<T>(fromNib name: String, withType type: T.Type) -> T {
        if let view = Bundle.main.loadNibNamed(name, owner: nil, options: nil)?.first as? T {
            return view
        }

        fatalError("Could not load view with type " + String(describing: type))
    }
}
21

You could try:

UIView *firstViewUIView = [[[NSBundle mainBundle] loadNibNamed:@"firstView" owner:self options:nil] firstObject];
[self.view.containerView addSubview:firstViewUIView];
Enrico Susatyo
  • 19,372
  • 18
  • 95
  • 156
NJones
  • 27,139
  • 8
  • 70
  • 88
  • It's not precisely what you suggested. He said his "rootView.xib" would have a subView half the size of the screen named "containerView". And into containerView he wanted to load the contents of his nib "firstView.xib". – NJones Oct 19 '11 at 02:36
6

Create a XIB file :

File -> new File ->ios->cocoa touch class -> next

enter image description here

make sure check mark "also create XIB file"

I would like to perform with tableview so I choosed subclass UITableViewCell

you can choose as your requerment

enter image description here

XIB file desing as your wish (RestaurantTableViewCell.xib)

enter image description here

we need to grab the row height to set table each row hegiht

enter image description here

Now! need to huck them swift file . i am hucked the restaurantPhoto and restaurantName you can huck all of you .

enter image description here

Now adding a UITableView

enter image description here

name
The name of the nib file, which need not include the .nib extension.

owner
The object to assign as the nib’s File's Owner object.

options
A dictionary containing the options to use when opening the nib file.

first if you do not define first then grabing all view .. so you need to grab one view inside that set frist .

Bundle.main.loadNibNamed("yourUIView", owner: self, options: nil)?.first as! yourUIView

here is table view controller Full code

import UIKit

class RestaurantTableViewController: UIViewController ,UITableViewDataSource,UITableViewDelegate{

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let restaurantTableviewCell = Bundle.main.loadNibNamed("RestaurantTableViewCell", owner: self, options: nil)?.first as! RestaurantTableViewCell

        restaurantTableviewCell.restaurantPhoto.image = UIImage(named: "image1")
        restaurantTableviewCell.restaurantName.text = "KFC Chicken"

        return restaurantTableviewCell
    }
   // set row height
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 150
    }

}

you done :)

enter image description here

Nazmul Hasan
  • 10,130
  • 7
  • 50
  • 73
5

For Swift 4.2

Let's assume you have a class named NibView and associated nib file is NibView.xib

class NibView: UIView {

    class func getScreen() -> NibView {
        let xib = Bundle.main.loadNibNamed(String(describing :self), owner: self, options: nil)
        let me = xib![0] as! NibView
        return me
    }

}

create an instance of the class and add in your view with your specific layout whatever you want

let myView = NibView.getScreen()
self.yourView.addSubview(myView)
Noshaid Ali
  • 127
  • 1
  • 12
4

For swift 3 & 4

let customView = Bundle.main.loadNibNamed("CustomView", owner: nil, options: nil)?.first as? CustomView
raed
  • 4,887
  • 4
  • 30
  • 49