iOS How to make custom reusable UIView using XIB


Example

Following example shows steps involved in initializing a view from XIB.

This is not a complex operation but exact steps need to be followed in order to do it right way first time, avoiding exceptions.

How does loadNibNamed Works

Main steps are:

  1. Create XIB
  2. Create class .h and .m
  3. Define outlets in .h
  4. Connect outlets between .h and XIB

See attached screenshot:

Label Object connected to myLabel IBOutlet UILabel variable

  1. Invoke loadNibNamed inside initWithCoder function of .m file. This is needed to ensure you can directly place UIView object into storyboard / Parent UIView XIB file and define it as your custom view. No other initialization code is needed once you load the storyboard / parent XIB. Your custom view can be added to other views just like other built-in Objective C view objects given in XCode.