0

How can I change the image in the right button of the navigation bar when I select a specific cell?

A good example is in the picture where the rightBarButtonItem image is different based on the selected cell:

enter image description here

Kerberos
  • 4,036
  • 3
  • 36
  • 55
aaallleeexxx918
  • 171
  • 3
  • 11

2 Answers2

1

You can simply add a right bar button item in the navigation bar with this code in the viewDidLoad:

let navBarbutton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.bookmarks, target: self, action: nil)
navItem.rightBarButtonItem = navBarbutton

(change the systemItem with your image)

Add an IBOutlet like this:

@IBOutlet weak var navItem: UINavigationItem!

and connect it to the navigation item in your storyboard.

Then in your didSelectRowAtIndexPath you can handle it with this sample code:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if (indexPath.row == 0)
    {
        navItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.add, target: self, action: nil)
    }
    else if (indexPath.row == 1)
    {
        navItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.camera, target: self, action: nil)
    }
}
Kerberos
  • 4,036
  • 3
  • 36
  • 55
1

You can try below code to creating and set UIBarButtonItem as navigationItem.

let updateButton = UIBarButtonItem(image: YourImage, style: .plain, target: self, action: #selector(buttonAction))
navigationItem.rightBarButtonItem = updateButton

@objc func buttonAction() {
}

So in your didSelectRowAt indexPath delegate method according to condition create and set UIBarButtonItem as required.

vivekDas
  • 1,248
  • 8
  • 12