Image on IOS navigation bar button

Asked

Viewed 280 times

0

I need to add two buttons in the navigation bar of my app, but what I need to use an external image (already imported to the project) it does not appear.

    override func viewDidLoad() {
        super.viewDidLoad()

         //Esse botão aparece (icone da própria biblioteca)

        let rightShareBarButtonItem:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.action, target: self, action: #selector(ViewController.shareTapped))

        //Esse ícone não aparece, estou tentando carregar uma imagem interna - já importada ao projeto

        let rightInfoBarButtonItem:UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "info.png"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.infoTapped))

        self.navigationItem.setRightBarButtonItems([rightInfoBarButtonItem, rightShareBarButtonItem], animated: true)
    }
  • 1

    One guess is that there isn’t enough space for the two buttons on this side of the bar. Have you tried adding just the custom button or adding it first to see if it appears? I didn’t notice anything wrong in the code...

  • So, I’ve put two buttons that have in the Xcode library itself and both appeared, including already put text in which its size is larger than the icon and tb appeared, the only thing that does not appear are external images...

  • 1

    The image is there in xcassets exactly with the name you are calling her, right?

  • I’m new to iOS development and didn’t know that icons should be on xcassets, for me they were the same as the other images where we just add to the project. But I created a new Assets.xcassets and it worked. Again thank you very much, it completely solved my problem.

1 answer

2

Your Viewcontroller has a Navigationcontroller ? Because if he doesn’t, his buttons won’t appear on the screen.

How to add a navigationController to your viewController via code.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    window = UIWindow(frame: UIScreen.main.bounds)

    let controller = ViewController()

    let navigationController = UINavigationController(rootViewController: controller)

    window?.rootViewController = navigationController
    window?.makeKeyAndVisible()


    return true
}

Now I saw storyboard.

inserir a descrição da imagem aqui

Then it should stay that way

inserir a descrição da imagem aqui

Now inside your Viewcontroller independent if it is via code, or by storyboard, this should work.

    let image = UIImageView(image: #imageLiteral(resourceName: "image"))

    let rightButton = UIBarButtonItem(image: image.image, style: .plain, target: nil, action: nil)

    navigationItem.setRightBarButton(rightButton, animated: true)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.