How do I put different images in rightBarButtonItem when I click on cell in xcode?

61 Views Asked by At

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

2

There are 2 best solutions below

0
Kerberos On BEST ANSWER

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)
    }
}
0
vivekDas On

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.