How to add / use default icons to navigation bar

28.6k views Asked by At

I want to use some of default iOS icons i.e.
enter image description here

in navigation bar.
Basically I don't know how to call image of that item (directly from native library - I know how to download it and place as custom image:)):

   var myButton:UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
   myButton.addTarget(self, action: "reload", forControlEvents: UIControlEvents.TouchUpInside)
   myButton.setImage(???, forState: <#UIControlState#>)
3

There are 3 answers

1
Dharmesh Kheni On BEST ANSWER

You can use UIBarButtonSystemItem this way:

let button = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: "someAction")
navigationItem.leftBarButtonItem = button

Result for leftBarButtonItem:

enter image description here

If you want to set it at right side you can use this code:

navigationItem.rightBarButtonItem = button

Result for rightBarButtonItem:

enter image description here

1
Nitin Nain On

Swift: These are the most commonly used options:

To Use custom image with original colour:

let customImageBarBtn1 = UIBarButtonItem(
    UIImage(named: "someImage.png").withRenderingMode(.alwaysOriginal),
    style: .plain, target: self, action: #selector(handleClick))

To Use custom image with tint colour:

let customImageBarBtn2 = UIBarButtonItem(
    UIImage(named: "someImage.png").withRenderingMode(.alwaysTemplate),
    style: .plain, target: self, action: #selector(handleClick))

Or use system provided buttons:

let systemBarBtn = UIBarButtonItem(
    barButtonSystemItem: .search,
    target: self, action: #selector(handleClick))

Then add any one of these buttons to the navigationItem:

navigationItem.leftBarButtonItems = [customImageBarBtn1, customImageBarBtn2]
navigationItem.rightBarButtonItems = [systemBarBtn]
// OR you can use this if there's only one item.
navigationItem.rightBarButtonItem = systemBarBtn

For custom Images: As a starting size, 22ptx22pt images work well for the default iPhone Navigation Bar size.

0
Sanjay Mishra On

In swift 4.3

let btnRefresh = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.refresh, target: self, action: #selector(targeted function to invoke))

   //If you want icon in left side
    navigationItem.leftBarButtonItem = btnRefresh

   //If you want icon in right side
    navigationItem.rightBarButtonItem = btnRefresh