Add custom view(xib) as navigation bar ios

260 Views Asked by At

I am tring to show a custom view as navigation controller. I have created the view seperately as the design is complex. How can I integrate this view in place of navigation bar. The height of the view is greater than default height of navigation bar.

1

There are 1 best solutions below

0
Neklas On

Here is what I am doing, hope that it will help you.

First, add these codes below into your UIViewExtension+NibLoad.swift

import UIKit

class NibView: UIView {

    var view: UIView!
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // Setup view from .xib file
        xibSetup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        // Setup view from .xib file
        xibSetup()
    }
}

private extension NibView {
    
    func xibSetup() {
        backgroundColor = UIColor.clear
        view = loadNib()
        // use bounds not frame or it'll be offset
        view.frame = bounds
        // Adding custom subview on top of our view
        addSubview(view)
        
        view.translatesAutoresizingMaskIntoConstraints = false
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[childView]|",
                                                      options: [],
                                                      metrics: nil,
                                                      views: ["childView": view!]))
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[childView]|",
                                                      options: [],
                                                      metrics: nil,
                                                      views: ["childView": view!]))
    }
}

extension UIView {
    /** Loads instance from nib with the same name. */
    func loadNib() -> UIView {
        let bundle = Bundle(for: type(of: self))
        let nibName = type(of: self).description().components(separatedBy: ".").last!
        let nib = UINib(nibName: nibName, bundle: bundle)
        return nib.instantiate(withOwner: self, options: nil).first as! UIView
    }
}

Second, here is your CustomNavbar

import UIKit

// It is just a UIView
class YourCustomNavBar: NibView {
    
}

Then, enter image description here

Next, enter image description here

Finally, enter image description here