Swift Custom NavBar Back Button Image and Text

2019-03-09 05:36发布

I need to customise the look of a back button in a Swift project.

Here's what I have: Default Back Button

Here's what I want: Custom Back Button

I've tried creating my own UIBarButtonItem but I can't figure out how to get the image to be beside the text, rather than as a background or a replacement for the text.

let backButton = UIBarButtonItem(title: "Custom", style: .Plain, target: self, action: nil    )
//backButton.image = UIImage(named: "imageName") //Replaces title
backButton.setBackgroundImage(UIImage(named: "imageName"), forState: .Normal, barMetrics: .Default) // Stretches image
navigationItem.setLeftBarButtonItem(backButton, animated: false)

9条回答
【Aperson】
2楼-- · 2019-03-09 06:22

Swift 4.2 Add this functions ViewController

func addNavigationBarButton(imageName:String,direction:direction){
    var image = UIImage(named: imageName)
    image = image?.withRenderingMode(.alwaysOriginal)
    switch direction {
    case .left:
       self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style:.plain, target: nil, action: #selector(goBack))
    case .right:
       self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style:.plain, target: nil, action: #selector(goBack))
    }
}

@objc func goBack() {
    navigationController?.popViewController(animated: true)
}

enum direction {
    case right
    case left
}

Using you should use here

viewDidLoad()

addNavigationBarButton(imageName: "ic_back", direction:.left)
查看更多
对你真心纯属浪费
3楼-- · 2019-03-09 06:23

swift 3

    extension UIViewController {

        func setBackButton(){
            let yourBackImage = UIImage(named: "backbutton")
            navigationController?.navigationBar.backIndicatorImage = yourBackImage
            navigationController?.navigationBar.backIndicatorTransitionMaskImage = yourBackImage
        }

    }
查看更多
甜甜的少女心
4楼-- · 2019-03-09 06:23

I have tried all the above and all make the custom image without changing the text The only one worked for me is from this answer

let backBTN = UIBarButtonItem(image: UIImage(named: "Back"), 
                              style: .plain, 
                              target: navigationController, 
                              action: #selector(UINavigationController.popViewController(animated:)))
navigationItem.leftBarButtonItem = backBTN
navigationController?.interactivePopGestureRecognizer?.delegate = self
查看更多
登录 后发表回答