self.navigationItem.rightBarButtonItem = Button not working?

1k views Asked by At

I have a bit of code bellow which creates an bar button item to then add to the navigation bar on the right side like many apps do.

The problem I am having is that the button/image do not show up at all.

How can I fix this?

FYI: This code runs as a setup() func after all other code runs in the view did load.

        let image = UIImage(systemName: "paperplane")?.withTintColor(.black, renderingMode: .alwaysOriginal)
        
        let button = UIBarButtonItem(image: image,
                                     style: .plain,
                                     target: self,
                                     action: #selector(showDMController))
        
        self.navigationItem.rightBarButtonItem = button
2

There are 2 answers

0
Habin Lama On

Try this code tested and working for me.

let image = UIImage(systemName: "paperplane")?.withTintColor(.black, renderingMode: .alwaysOriginal)
    
    let button = UIBarButtonItem(image: image,
                                 style: .plain,
                                 target: self,
                                 action: #selector(showDMController))
    
    self.navigationController?.navigationBar.topItem?.rightBarButtonItem = button

I have added topItem to add rightBarButton. If this does not solve your problem let me know.

0
Vasilis D. On

In your UIViewController class write this code in viewDidLoad() method

override func viewDidLoad() {
    super.viewDidLoad()
    let rightBarButton = UIButton(type: .custom)
    rightBarButton.contentMode = .scaleAspectFit
    rightBarButton.setImage(yourImage, for: .normal)
    rightBarButton.setImage(yourImage, for: .selected)
    rightBarButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(yourGestureRecognizer)))
    navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBarButton)
    navigationItem.rightBarButtonItem?.style = .plain
}

@objc func yourGestureRecognizer() {
   print("yourGestureRecognizer called")
}