Adjust position of custom Navigation Back Button

2019-08-20 13:35发布

I am using a custom image as the back button of my Navigation Controller but the problem is that the image is not aligned correctly with the title and the right button item. I've been trying to move the back button down a few pixels with no success.

extension UINavigationController {

       func addBackButton() {
            let imgBack = UIImage(named: "ic_back")
            navigationBar.backIndicatorImage = imgBack
            navigationBar.backIndicatorTransitionMaskImage = imgBack
            navigationBar.topItem?.backBarButtonItem = UIBarButtonItem(title: "",
                                                                       style: .plain,
                                                                       target: self,
                                                                       action: nil)
        }
}

This is what it looks like now:

enter image description here

As you can see I need to move the back button down a little, any help would be much appreciated.

1条回答
干净又极端
2楼-- · 2019-08-20 13:43

This is my code for a custom back button. I added on viewDidLoad() with the image below. Maybe you need to test with your image how to size it correctly. And you can remove the part with the label.

            let backButtonView = UIView(frame: CGRect(x: 0, y: 0, width: 60, height: 44))
            let imageView = UIImageView(image: UIImage(named: "back-arrow"))
            imageView.frame = CGRect(x: -5, y: 11, width: 12, height: 22)
            imageView.image = imageView.image!.withRenderingMode(.alwaysTemplate)
            imageView.tintColor = .blue
            let label = UILabel(frame: CGRect(x: 10, y: 0, width: 40, height: 44))
            label.textColor = .blue
            label.text = "Back"
            backButtonView.addSubview(imageView)
            backButtonView.addSubview(label)
            backButtonView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(backButtonClicked)))
            let barButton = UIBarButtonItem(customView: backButtonView)
            navigationItem.leftBarButtonItem = barButton

enter image description here

查看更多
登录 后发表回答