1

I have designed UIView as XIB with class. Can I use this xib, as existed example for other UIViews? So, I want create this UIView once and after use it in different parts of application.

Golovanov Dmytrii
  • 527
  • 1
  • 6
  • 20

2 Answers2

1

Yes, you can instantiate it anywhere and as much as you want:

Answer showing how to instantiate as a view: How to initialize/instantiate a custom UIView class with a XIB file in Swift

Answer showing how to instantiate as a reusable cell for an UITableView or UICollectionView: Custom UITableViewCell from nib in Swift

Gustavo Vollbrecht
  • 3,188
  • 2
  • 19
  • 37
1

Yes you can.

Once you've created the XIB, create a UIView class, assign that class to the XIB's file owner. Create an IBOutlet of the whole XIB container view attach it to the UIView class, call it something like containerView

On your XIB's custom class add the following:

override init(frame: CGRect) {
super.init(frame: frame)

customInit()

}

func customInit() {

Bundle.main.loadNibNamed("YourNIBName", owner: self, options: nil)
addSubview(containerView)
containerView.autoresizingMask = [.flexibleHeigh, .flexibleWidth]


}

On any of your ViewControllers now :

let view = CustomNib(frame: CGRect(x: 0, y:0, width: 150, height: 150)

self.view.addSubview(view)

You can also create this via the storyboard simply assign the custom xib class to any UIView.

Here is a great resource that can also help: Swift 3 — Creating a custom view from a xib

Sam Bing
  • 2,794
  • 1
  • 19
  • 29
  • Thanks! I like some code like this, but only for one view, and don't want to do it with no ideas about many views. – Golovanov Dmytrii Apr 11 '18 at 14:10
  • You're welcome. This works great for reusing it throughout any of your apps view controllers, requires few lines to add programmatically and none to add it via the storyboard. – Sam Bing Apr 11 '18 at 14:44