Thursday, June 13, 2024
HomeIOS DevelopmentCustomized UIView subclass from a xib file

Customized UIView subclass from a xib file

I have already got a complete information about initializing views and controllers, however that one lacks a really particular case: making a customized view utilizing interface builder. ๐Ÿคทโ€โ™‚๏ธ

Loading xib information

Utilizing the contents of a xib file is a fairly rattling simple activity to do. You should use the next two strategies to load the contents (aka. the view hierarchy) of the file.

let view = UINib(
    nibName: "CustomView", 
    bundle: .major
    withOwner: nil, 
    choices: nil
).first as! UIView


view.body = self.view.bounds

The snippet above will merely instantiate a view object from the xib file. You may have a number of root objects within the view hierarchy, however this time let’s simply decide the primary one and use that. I assume that in 99% of the instances that is what you may want with the intention to get your customized views. Additionally you possibly can prolong the UIView object with any of the options above to create a generic view loader. Extra on that later… ๐Ÿ˜Š

This methodology is fairly easy and low-cost, nevertheless there’s one little disadvantage. You may’t get named pointers (shops) for the views, however just for the foundation object. In case you are placing design components into your display screen, that is fantastic, but when you could show dynamic information, you may need to attain out for the underlying views as properly. ๐Ÿ˜ƒ

Customized views with shops & actions

So the correct option to load customized views from xib information goes one thing like this:

Inside your customized view object, you instantiate the xib file precisely the identical manner as I instructed you proper up right here. ๐Ÿ‘† The one distinction is that you simply need not use the item array returned by the strategies, however you must join your view objects by the interface builder, utilizing the File’s Proprietor as a reference level, plus a customized container view outlet, that’ll include every part you want. ๐Ÿคจ

class CustomView: View {

    @IBOutlet weak var containerView: UIView!

    @IBOutlet weak var textLabel: UILabel!

    override func initialize() {

        let title = String(describing: sort(of: self))
        let nib = UINib(nibName: title, bundle: .major)
        nib.instantiate(withOwner: self, choices: nil)

        self.containerView.translatesAutoresizingMaskIntoConstraints = false
            self.containerView.topAnchor.constraint(equalTo: self.topAnchor),
            self.containerView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
            self.containerView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
            self.containerView.trailingAnchor.constraint(equalTo: self.trailingAnchor),

So the initialize methodology right here is simply loading the nib file with the proprietor of self. After the loading course of completed, your outlet pointers are going to be stuffed with correct values from the xib file. There may be one last item that we have to do. Even the views from the xib file are “programmatically” linked to our customized view object, however visually they are not. So now we have so as to add our container view into the view hierarchy. ๐Ÿค


If you wish to use your customized view object, you simply should create a brand new occasion from it – inside a view controller – and at last be at liberty so as to add it as a subview!

One phrase about bounds, frames aka. springs and struts: fucking UGLY! That is two phrases. They’re thought-about as a nasty observe, so please use auto structure, I’ve a pleasant tutorial about anchors, they’re wonderful and studying them takes about quarter-hour. ๐Ÿ˜…

class ViewController: UIViewController {

    weak var customView: CustomView!

    override func loadView() {

        let customView = CustomView()
            customView.topAnchor.constraint(equalTo: self.view.topAnchor),
            customView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
            customView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            customView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
        self.customView = customView

    override func viewDidLoad() {

        self.customView.textLabel.textual content = "Lorem ipsum"

That is it, now you’ve a very working customized UIView object that masses a xib file with the intention to use it is contents. Wasn’t so dangerous, proper? ๐Ÿคช

Yet another further factor. In the event you do not prefer to deal with views programmatically otherwise you merely do not need to fiddle with the loadView methodology, simply take away it solely. Subsequent put the @IBOutlet key phrase proper earlier than your customized view class variable. Open your storyboard utilizing IB, then drag & drop a brand new UIView component to your controller and join the customized view outlet. It ought to work like magic. ๐Ÿ’ซ


I promised shops and actions within the heading of this part, so let’s discuss just a little bit about IBActions. They work precisely the identical as you’d anticipate them with controllers. You may merely hook-up a button to your customized view and delegate the motion to the customized view class. If you wish to ahead touches or particular actions to a controller, you need to use the delegate sample or go together with a easy block. ๐Ÿ˜Ž

Possession and container views

It’s doable to go away out all of the xib loading mechanism from the view occasion. We are able to create a set of extensions with the intention to have a pleasant view loader with a customized view class from a xib file. This fashion you do not want a container view anymore, additionally the proprietor of the file will be ignored from the sport, it is kind of the identical methodology as reusable cells for tables and collections created by Apple. ๐ŸŽ

It is best to know that going this manner you possibly can’t use your default UIView init strategies programmatically anymore, as a result of the xib file will deal with the init course of. Additionally in case you are making an attempt to make use of this type of customized views from a storyboard or xib file, you will not be capable of use your shops, as a result of the correspondig xib of the view class will not be loaded. In any other case in case you are making an attempt to load it manyally you may run into an infinite loop and ultimately your app will crash like hell. ๐Ÿ˜ˆ

import UIKit

extension UINib {
    func instantiate() -> Any? {
        return self.instantiate(withOwner: nil, choices: nil).first

extension UIView {

    static var nib: UINib {
        return UINib(nibName: String(describing: self), bundle: nil)

    static func instantiate(autolayout: Bool = true) -> Self {
        func instantiateUsingNib<T: UIView>(autolayout: Bool) -> T {
            let view = self.nib.instantiate() as! T
            view.translatesAutoresizingMaskIntoConstraints = !autolayout
            return view
        return instantiateUsingNib(autolayout: autolayout)

class CustomView: UIView {

    @IBOutlet weak var textLabel: UILabel!

Identical to with desk or assortment view cells this time you must set your customized view class on the view object, as an alternative of the File’s Proprietor. You must join your shops and mainly you are completed with every part. ๐Ÿคž


Any more you need to ALWAYS use the instantiate methodology in your customized view object. The excellent news is that the perform is generic, returns the correct occasion sort and it is extremely reusable. Oh, btw. I already talked about the dangerous information… ๐Ÿคช

There may be additionally yet another method by overriding awakeAfter, however I’d not depend on that resolution anymore. In many of the instances you possibly can merely set the File’s Proprietor to your customized view, and go together with a container, that is a secure guess. If in case you have particular wants you may want the second method, however please watch out with that. ๐Ÿ˜‰



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments