简体   繁体   中英

How can I add title and image on a bar buttonitem for a toolbar of navigation controller

How it is possible to add an image and text on a UIBarButtonItem on a navigation controller just like on modern apps such as Photos, ebay etc (see Toolbar )

I know this is possible in Interface Builder if you add a toolbar manually to a view but this is not possible if using navigation controller.

If you have a UIViewController in a UINavigationController you can set the left and the right bar button of the view controller with

// System item
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(action))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(action))
// Tittle
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Left Button", style: .plain, target: self, action: #selector(action))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Right Button", style: .plain, target: self, action: #selector(action))
// Image
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(action))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(action))
// Custom view
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: view)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: view)

This is as far as I got so far. This, however only displays a text right to the image:

   //Create a UIButton with an image on the left, and text to the right
    var buttonImage = #imageLiteral(resourceName: "Lab")
    var button : UIButton = UIButton(type: UIButtonType.custom)
    button.setImage(buttonImage, for: UIControlState.normal);
    button.setTitle("Caption", for: UIControlState.normal);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM