1

I am struggling to figure out how to load a xib from within a storyboard using Swift in XCode.

My main storyboard (Called TabBarNav.storyboard) is a Tab Bar View controller with 4 items (Home, Weight, Meals and Calories).

I have created a seperate XIB UIView called ViewWelcome.xib with corresponding class file ViewWelcome.swift.

The Home items view controller has a class file called "ViewControllerHome.swift"

When the Home tab bar item is touched I want to replace the existing view with the one within ViewWelcome.xib.

In ViewWelcome.xib I have made the files owner ViewControllerHome but when I run the app it is still showing the view that was created with the Home item when I originally created the storyboard.

Reason I am doing it this way: (A Mix of storyboard and xibs) I wanted each section (Home, Weight, Meals and Calories) to be seperate from the storyboard so that the SB doesnt become cluttered and to also later avoid merge issues in git when more than one person works on interface files. Storyboard

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
John Cogan
  • 1,034
  • 4
  • 16
  • 39

2 Answers2

1

Simplest way is to create & add your nib view in viewDidLoad

func viewDidLoad() {

    super.viewDidLoad()

    // create and add view from nib
    if let viewWelcome = UINib(nibName: " ViewWelcome", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as? ViewWelcome {
        viewWelcome.frame.size = self.view.size
        self.view.addSubview(viewWelcome)
    }
}

Otherwise refer to this

Jože Ws
  • 1,754
  • 17
  • 12
0

This is working for me . Give a try . .

let newView = Bundle.main.loadNibNamed("ViewWelcome", owner: self, options: nil)?.first as! ViewWelcome
self.view = newView
roy
  • 6,685
  • 3
  • 26
  • 39