Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse a uiview xib in storyboard

I typically like to create and design my uiviews in interface builder. Sometimes I need to create a single view in a xib that can be reused in multiple view controllers in a storyboard.

like image 524
Garfbargle Avatar asked May 19 '15 20:05

Garfbargle


People also ask

Should I use storyboard or xib?

When you want to see some flow without building the app, a storyboard is the best option. Also if you create static table views or more then one cell template, you can use a storyboard.


1 Answers

Reuse and render a xib in a storyboard.

Tested with Swift 2.2 & Xcode 7.3.1

1 ---- Create a new UIView named 'DesignableXibView'

  • File > New > File > Source > Cocoa Touch Class > UIView

2 ---- Create a matching xib file named 'DesignableXibView'

  • File > New > File > User Interface > View

3 ---- Set the file owner of the of the xib

  1. select the xib
  2. select file's owner
  3. set custom class to 'DesignableXibView' in the Identity Inspector.

Setting a Xib's Owner to a Custom Class

  • Note: Do not set the custom class of the view on the xib. Only the File Owner!

4 ---- DesignableXibView's Implementation

//  DesignableXibView.swift  import UIKit  @IBDesignable  class DesignableXibView: UIView {      var contentView : UIView?      override init(frame: CGRect) {         super.init(frame: frame)         xibSetup()     }      required init?(coder aDecoder: NSCoder) {         super.init(coder: aDecoder)         xibSetup()     }      func xibSetup() {         contentView = loadViewFromNib()          // use bounds not frame or it'll be offset         contentView!.frame = bounds          // Make the view stretch with containing view         contentView!.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]          // Adding custom subview on top of our view (over any custom drawing > see note below)         addSubview(contentView!)     }      func loadViewFromNib() -> UIView! {          let bundle = NSBundle(forClass: self.dynamicType)         let nib = UINib(nibName: String(self.dynamicType), bundle: bundle)         let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView          return view     }  } 

5 ---- Test your reuseable view in a storyboard

  1. Open your storyboard
  2. Add a view
  3. Set that view's Custom Class
  4. wait a sec ... BOOM!!

Xib Rendering Inside a Storyboard View Controller

like image 80
Garfbargle Avatar answered Sep 24 '22 19:09

Garfbargle