In this tutorial, I will create a subclass of UIView with xib.
In iOS, UI can be created by purely code or xib.
Personally, I always prefer xib. It is WYSIWYG and easy to update or modify.
if you create UI pure programmatically, it will be hundreds lines of code. And you will need to do geometry to layout the subviews. Using pure code is tedious and difficult to maintain (You are not able to see the UI until you launch the app).
Check the project on my github
let's begin the tutorial.
First, create a new iOS Single View project. Name it whatever you like. I name my own "SubclassUIViewExample".
Then, create a new subclass of UIView called "HJYView".
Different from create subclass of UIViewController, it does not come with a xib file.
Create a empty xib file, name it as "HJYView", same as .h and .m files just created.
Go to the interface builder page, put a white UIView and name it "HJYView" on the custom class tab. It is very important, otherwise the app will crash when it launches.
Put some UIs into the UIView. I put two UILabel and one UITextField. You can put anything you want in your project.Remove Autolayout if you want iOS 5.0 compatibility.
Connect outlet between XIB and .h file by click UI while holding ctrl-key.
Then go to HJYView.m file and write some code.
When I type something into inputTextFiled, outputLabel will display the same text with a random color.
Finally, go to HJYViewController.m file to add the custom view.
Command+R, run the simulator. Done!
Also, remember to set the autoresizingMake on xib if you want the view display the UIVIew correctly in different kind of size of screens.