Search code examples
swiftuinavigationbar

Make text as UINavigationController back button


I need to make this kind of navigation bar

enter image description here

But I don't know how can I set backBarButton as text. Should I create xib that will replace my navigation bar or I can do it programmatically


Solution

  • In viewDidLoad set your custom button navBar:

    let button = UIButton(type: .custom)
        //Set the image
        button.setImage(UIImage(systemName: "chevron.backward"), for: .normal)
        //Set the title
        button.setTitle("Yourtitle", for: .normal)
        //Add target
        button.addTarget(self, action: #selector(callMethod), for: .touchUpInside) //call button tap action
        // Add insets padding
        let spacing: CGFloat = -10 // the amount of spacing to appear between image and title
        button.imageEdgeInsets = UIEdgeInsets(top: 0, left: spacing, bottom: 0, right: 0)
        button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) // customize your button titleEdgeInsets if you want
        //Create bar button
        let barButton = UIBarButtonItem(customView: button)
        navigationItem.leftBarButtonItem = barButton
    

    After that create your function for button tap:

    @objc fileprivate func callMethod() {
        print("Your code here")
    }