image for nav bar button item swift

swift add navigation bar button programmatically
add image to navigation bar swift
add custom view to navigation bar ios swift
navigation bar button item image
custom navigation bar swift
add button to navigation bar swift
rightbarbuttonitem not showing swift
custom large title navigation bar swift

I want to display an image in the left hand side of my nav bar in swift.

I have tried adding a nav bar button item and setting an image there.

The problem is that I have to use a really small image for it to fit in the nav bar nicely. But making such a small image leads to pixelation especially on the bigger phone iPhone 6 and 6 Plus.

Is there a way to use a good quality image and then set the frame to fit within the bounds of the nav bar?

My attempt:

var image = UIImage(named: "Harp.png")

image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)

self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
self.navigationItem.leftBarButtonItem.frame = CGRectMake(0, 0, 53, 31)
//image.frame = CGRectMake(0, 0, 53, 31)

I tried putting the frame on the image first and then on the bar button item. But this is throwing up an error:

Type of expression is ambiguous without more context.

Try This

let button = UIButton(type: UIButtonType.Custom)
button.setImage(UIImage(named: "yourImageName.png"), forState: UIControlState.Normal)
button.addTarget(self, action:Selector("callMethod"), forControlEvents: UIControlEvents.TouchDragInside)
button.frame=CGRectMake(0, 0, 30, 30)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.leftBarButtonItems = [newBackButton,barButton]

For Swift 3

let button = UIButton.init(type: .custom)
button.setImage(UIImage.init(named: "yourImageName.png"), for: UIControlState.normal)
button.addTarget(self, action:#selector(ViewController.callMethod), for:.touchUpInside)
button.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30) //CGRectMake(0, 0, 30, 30)
let barButton = UIBarButtonItem.init(customView: button)
            self.navigationItem.leftBarButtonItem = barButton

Swift 4

let button = UIButton(type: UIButton.ButtonType.custom)
button.setImage(UIImage(named: "getstarted"), for: .normal)
button.addTarget(self, action:#selector(callMethod), for: .touchDragInside)
button.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.leftBarButtonItems = [barButton]

Here is action

@objc func callMethod() {   
    //do stuff here
 }

How to set image for bar button with swift?, And if you want same transaction as navigation controller have when you go back with For swift 3.0: barButtonItem.image = UIImage(named: "image"). In this tutorial we’re going to learn how to add buttons and images to navigation bar in SwiftUI’s NavigationView. In order to achieve this goal we’re going to use the navigationBarItems modifier which lets you specify leading and/or trailing bar items (e.g., buttons, images or other SwiftUI views).

Use this code:

self.navigationItem.leftBarButtonItem = nil

let button = UIButton(type: .custom)
button.setImage(UIImage (named: "ChatTab"), for: .normal)
button.frame = CGRect(x: 0.0, y: 0.0, width: 35.0, height: 35.0)
//button.addTarget(target, action: nil, for: .touchUpInside)
let barButtonItem = UIBarButtonItem(customView: button)

let button2 = UIButton(type: .custom)
button2.setImage(UIImage (named: "ActivityTab"), for: .normal)
button2.frame = CGRect(x: 0.0, y: 0.0, width: 35.0, height: 35.0)
//button.addTarget(target, action: nil, for: .touchUpInside)

let barButtonItem2 = UIBarButtonItem(customView: button2)
self.navigationItem.rightBarButtonItems = [barButtonItem, barButtonItem2]

Output:

Navigation Bar Customisation. Part 1, Customisation of a navigation bar is one of the first tasks a junior iOS-developer takes up. When we need more (for example, set an image as a title, make a two​-lined There are several ways to instantiate a bat button item. Situation:In Swift 2.0, I have a Navigation Bar with a Button Bar Item on the right and a Tool Bar with a Button Bar Item on the right. When the Navigation Bar’s Button Bar Item is tapped I want it disabled and then reenabled when the Tool Bar’s Button Bar Item is tapped. I tried the following and it didn’t work. :(Navigation Button Bar Item:

Swift 4 and 5:

let imageView = UIImageView(image: UIImage(named: "Harp"))
let buttonItem = UIBarButtonItem(customView: imageView)
self.navigationItem.leftBarButtonItem = buttonItem

How to add a bar button to a navigation bar, You can add buttons to the left and right side of a navigation bar, and you can add more than one to either side. Note: usually bar button items  Navigation bars are one of the most common user interface components in iOS, so being able to add buttons to them is something you'll do a lot. You can add buttons to the left and right side of a navigation bar, and you can add more than one to either side. Note: usually bar button items don't belong to the UINavigationBar directly.

There is a way to use images of different sizes, depending on the device. It's called an Asset Catalog. You'll probably already have one in your project, or if not, you can add one with File > New > File > Resource > Asset Catalogue.

Within your Asset Catalog, you can have multiple 'Image Sets' (these will be shown down the left-hand side). Add a new Image Set with the '+' at the bottom. For each Image Set, you can supply different images (e.g. of different sizes) for each of @1x, @2x, and @3x.

Then, to use one of these images in code, you simply use UIImage(named: "name_of_image_set") - note no extension. The correct image will be loaded, depending on the device.

Hope this helps!

Customizing Your App's Navigation Bar, Swift; Objective-C Create custom titles, prompts, and buttons in your app's navigation bar. of UIBarButtonItems on the right side of the navigation bar: a button with a title, a button with an image, and a button with a UISegmentedControl . This code shows how to set a segmented control as the right bar button item:. Change navigation bar color. In order to change color of navigation bar for all view controllers, you have to set it in AppDelegate.swift file; Add following code to didFinishLaunchingWithOptions

Swift 5, XCode 11 to make Navigation Bar Item with rounded image, image from assets or to download from URL.

1) New file: UIBarButtonItem+RoundedView.swift

import Foundation

class ImageBarButton : UIView {
    var imageView: UIImageView!
    var button: UIButton!

    convenience init(withUrl imageURL: URL? = nil, withImage image: UIImage? = nil, frame: CGRect = CGRect(x: 0, y: 0, width: 40, height: 40)) {
        self.init(frame: frame)

        imageView = UIImageView(frame: frame)
        imageView.backgroundColor = .white
        imageView.layer.cornerRadius = frame.height/2
        imageView.clipsToBounds = true
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        addSubview(imageView)

        button = UIButton(frame: frame)
        button.backgroundColor = .clear
        button.setTitle("", for: .normal)
        addSubview(button)

        if let url = imageURL { // you can use pods like Nuke or Kingfisher 
         URLSession(configuration: .default).dataTask(with: URL(string: imageUrl)!) {[weak self] (data, response, error) in
          if let data = data , let image = UIImage(data: data) {
              DispatchQueue.main.async {
                self?.imgView.image = image
              }
           }
         }.resume()
        } else if let image = image {
            self.imageView.image = image
        }
    }

    func load()-> UIBarButtonItem {
        return UIBarButtonItem(customView: self)
    }
}

2) Add navigation bar items, you can use navigationItem.rightBarButtonItems, navigationItem.leftBarButtonItems:

private func initalizeNavigationBarItems() {
    let searchBarButtonView = ImageBarButton(withImage: #imageLiteral(resourceName: "greenSearchIcon")) // Assets
    searchBarButtonView.button.addTarget(self, action: #selector(presentSearchViewController), for: .touchUpInside)

    if let user = AccountManager.currentUser, let userProfilePictureURL = user.imageUrl { // API Url
        let profileBarButtonView = ImageBarButton(withUrl: userProfilePictureURL)
        profileBarButtonView.button.addTarget(self, action: #selector(presentMoreViewController), for: .touchUpInside)
        navigationItem.rightBarButtonItems = [searchBarButtonView.load(), profileBarButtonView.load()]
    } else {
        let profileBarButtonView = ImageBarButton(withImage: #imageLiteral(resourceName: "profileIcon"))
        profileBarButtonView.button.addTarget(self, action: #selector(presentMoreViewController), for: .touchUpInside)
        navigationItem.rightBarButtonItems = [searchBarButtonView.load(), profileBarButtonView.load()]
    }
}

@objc func presentMoreViewController(_ sender: Any) {
    // present MoreViewController
}

@objc func presentSearchViewController(_ sender: Any) {
    // present SearchViewController
}

Preview

Introduction to Bar Button Items, UIBarButtonItem allows us to add additional buttons in our navigation bar. image showing bar button items. To support the creating, editing, and discarding actions​,  Alert Buttons Outline Buttons Split Buttons Animated Buttons Fading Buttons Button on Image Social Media Buttons Read More Read Less Loading Buttons Download Buttons Pill Buttons Notification Button Icon Buttons Next/prev Buttons More Button in Nav Block Buttons Text Buttons Round Buttons Scroll To Top Button

Customize Navigation Bar iOS Tutorial, The look of the Navigation Bar can be customized. Navigation Bar Style is set to black and the tint color is set to yellow, this will change the bar button items to yellow. The Swift Logo image is assigned to the Image view. To turn it from an “Item” button into a “+” button, you need to adjust the Bar Button Item’s attributes. Click on the button, either in the navigation bar itself or on the document outline for the Storyboard, and choose the Attributes Inspector for the control. Then change the System Item property from “Custom” to “Add”:

How to build resizing Image in Navigation Bar with Large Title, view raw Controller.swift hosted with ❤ by GitHub Margin from bottom anchor of NavBar to bottom anchor of Image for Large NavBar state. static let  How to make custom UINavigationController back button image without title (Swift) easiest way to customize navigation controller back button. a Custom Action for the Center Tab Bar Item.

image and text for nav bar button item. swift, I saw the answer for this question for adding an image to the left nav bar item. And I did it successfully. But I also want to add a small text next to the image. Adding Buttons to Containers. Use buttons for any user interface element that triggers actions on press. Buttons automatically adapt their visual style to match the expected style within these different containers and contexts. For example, to create a list cell that triggers an action when selected by the user, add a button to the list’s

Comments
  • why not use asset catalogue ?
  • Vinay is right. Using an asset catalogue is easy and automatic. Correct me if I'm wrong but I use @1,@2,@3 the following resolutions: 44x44, 88x88 and 132x132 pixels. ALSO, sometimes I need to correct the size using the image insets (if you have the button in IBuilder you might fix it from there).
  • one issue, the action is not being triggered? I have an action of "tryLogout" and a func tryLogout() but it the logout function is not being triggered?
  • oh apologies, I see it's just the event type that needs to change
  • Are you sure the second one is for Swift 3? I recalled that in Swift 3, all the method's parameters will have label. But your button.addTarget(self... doesn't have label for its first parameter.
  • Worked for me (Swift 3.0). Forgot to set the frame xD
  • What if i want to add a small text next to the image? for example i want to show how many coins the user have. so i need to show a coins image and the number of coins next to it. how can it be done? thanks.
  • While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
  • @double-beep The accepted answer does none of that. And as you can see it's a poor answer. I will delete my better solution after you read this.
  • No, you don't need this and I didn't force you to delete your answer. You should better not do it. Of course, code-only solutions are awesome, but solutions with explanations are excellent and take more upvotes.
  • the problem was that the bigger images were extending past the nav bar. Got it sorted with Avijit's solution