Search code examples
iosxcodeswiftuinavigationcontrolleruiimage

swift - navigation controller remove back button arrow


I have an application in swift, where the view controllers are inbedded in a navigation controller, now in the 2nd and 3rd viewcontroller, on the back button, there is a blue arrow pointing backwards (it is there by default). I have tried to remove this, but when I want to have an image there, the image gets all squished up. Does anyone know how you would go about removing the back-button arrow, and replace it with an image? Thanks alot!


Solution

  • Use this....

    Set Text:

    let backBtn = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: self, action: "BtnTapBack:")
    navigationItem.leftBarButtonItem = backBtn
    navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "YourFontName", size: 20)!], forState: UIControlState.Normal)
    

    Set Image:

    let image = UIImage(named:"YourImageName") as UIImage!
    var btnBack:UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
    btnBack.addTarget(self, action: "BtnTapBack:", forControlEvents: UIControlEvents.TouchUpInside)
    btnBack.setImage(image, forState: UIControlState.Normal)
    btnBack.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
    btnBack.sizeToFit()
    var myCustomBackButtonItem:UIBarButtonItem = UIBarButtonItem(customView: btnBack)
    self.navigationItem.leftBarButtonItem  = myCustomBackButtonItem
    

    Action go to the previous viewcontroller

    @IBAction func BtnTapBack(sender: UIButton) {
            navigationController?.popViewControllerAnimated(true)
    }