Search code examples
iosswiftiphonexcodeuinavigationcontroller

How to make a custom navigation bar with logo and a text in the navigation in iOS?


Since I am from an hybrid app background I want to achieve an UI in iOS which contains a logo and a text. Below is a blue strip which contains a "Back" and a "Registration" as the title. On Clicking back, it goes to the previous controller. How can I achieve this UI? I tried with a given code below: But I am not sure how to proceed further.

func addNavBarImage() {
        let navController = navigationController!
        let image = UIImage(named: "logo-signIn6.png") //Your logo url here
        let imageView = UIImageView(image: image)
        let bannerWidth = navController.navigationBar.frame.size.width
        let bannerHeight = navController.navigationBar.frame.size.height
        let bannerX = bannerWidth / 2 - (image?.size.width)! / 2
        let bannerY = bannerHeight / 2 - (image?.size.height)! / 2
        imageView.frame = CGRect(x: bannerX, y: bannerY, width: bannerWidth, height: bannerHeight)
        imageView.contentMode = .scaleAspectFit
        navigationItem.titleView = imageView
    }

Below is the image of UI which I want to achieve .enter image description here


Solution

  • You can assign a custom view to navigationItem.titleView. Here is a really simple code to assign an image and a text to titleView. I encourage you to create a separate view class, where you would define your custom view, that you then assign to titleView

    override func viewDidLoad() {
        super.viewDidLoad()
    
        let imageView = UIImageView()
        imageView.heightAnchor.constraint(equalToConstant: 30).isActive = true
        imageView.widthAnchor.constraint(equalToConstant: 30).isActive = true
    
        let titleLabel = UILabel()
        titleLabel.text = "Your title"
    
        let stackView = UIStackView(arrangedSubviews: [imageView, titleLabel])
        stackView.spacing = 5
        stackView.alignment = .center
    
        // This will assing your custom view to navigation title. 
        navigationItem.titleView = stackView
    }