Adding a logo in Navigation Bar that is left aligned - ios

I have been stumped on how to get an image in a NavigationBar that is left aligned. I understand how to replace the title in the center.
Basically, I have a view controller embedded in a Navigation Bar Controller. In that view controller, I have a search form in the middle and a bar button on the right and I am trying to fit in a logo that is an image to the left side.
Below is the what I understand how to put an image but how do I get it left aligned?
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
imageView.contentMode = .ScaleAspectFit
let image = UIImage(named: "imageName")
imageView.image = image
navigationItem.titleView = imageView

You can assign an array of items to the leftBarButtonItems property of the navigationBar. You should add an array because there is usually no space between the left side and the logo, and this doesn't look great. Here is an example:
func setUpUI() {
let logoImage = UIImage.init(named: "logoImage")
let logoImageView = UIImageView.init(image: logoImage)
logoImageView.frame = CGRectMake(-40, 0, 150, 25)
logoImageView.contentMode = .ScaleAspectFit
let imageItem = UIBarButtonItem.init(customView: logoImageView)
let negativeSpacer = UIBarButtonItem.init(barButtonSystemItem: .FixedSpace, target: nil, action: nil)
negativeSpacer.width = -25
navigationItem.leftBarButtonItems = [negativeSpacer, imageItem]
}
The negative spacer to the left of it will push it over a bit, and you can adjust it from there.

For iOS 11 we need to add constraints to the image view of the BarButtomItem
func addLeftBarIcon(named:String) {
let logoImage = UIImage.init(named: named)
let logoImageView = UIImageView.init(image: logoImage)
logoImageView.frame = CGRect(x:0.0,y:0.0, width:60,height:25.0)
logoImageView.contentMode = .scaleAspectFit
let imageItem = UIBarButtonItem.init(customView: logoImageView)
let widthConstraint = logoImageView.widthAnchor.constraint(equalToConstant: 60)
let heightConstraint = logoImageView.heightAnchor.constraint(equalToConstant: 25)
heightConstraint.isActive = true
widthConstraint.isActive = true
navigationItem.leftBarButtonItem = imageItem
}
All the best

Per #Warrior's answer,
For Objective-C, iOS11+ and relative layout for the logo.
// create Youtube icon imageView
UIImageView *youtubeImageView = [[UIImageView alloc] init];
youtubeImageView.translatesAutoresizingMaskIntoConstraints = false;
youtubeImageView.contentMode = UIViewContentModeScaleAspectFit;
youtubeImageView.image = [UIImage imageNamed:#"youtube_icon"];
UIBarButtonItem *imageItem = [[UIBarButtonItem alloc] initWithCustomView:youtubeImageView];
// set constraints
float width = self.view.frame.size.width * 0.3;
float height = width * 178 / 794; // width * 1/ratio
[youtubeImageView.widthAnchor constraintEqualToConstant:width].active = true;
[youtubeImageView.heightAnchor constraintEqualToConstant:height].active = true;
self.navigationItem.leftBarButtonItem = imageItem;

Create a BarButton item with Image.
Assign it as Left Bar Button Item to Navigation Bar as follows.
Objective C
UIBarButtonItem *logo = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:"imageName"] style:UIBarButtonItemStylePlain target:self action:#selector(methodName)];
self.navigationItem.leftBarButtonItem = logo;
SWIFT
let logo = UIBarButtonItem(image: UIImage (named: "imageName"), style: UIBarButtonItemStyle.plain, target: self, action: methodName)
self.navigationItem.leftBarButtonItem = logo
Hope it helps..

Related

Navigation Bar Items not left aligned

I have a navigationBar where I would like to have a button on the left, a activityIndicator as title and a doneButton on the right. This is what I tried:
let activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
let googleImage = UIImage(named: "google")!
let googleButton = UIBarButtonItem(image: googleImage, style: .plain, target: self, action: #selector(googleButtonTapped))
googleButton.image = UIImage(named: "google")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
navigationController?.navigationBar.barTintColor = UIColor.blueCustom
navigationController?.navigationBar.tintColor = UIColor.white
activityIndicator.hidesWhenStopped = true
activityIndicator.color = .white
self.navigationItem.titleView = self.activityIndicator
self.navigationItem.leftBarButtonItem = googleButton
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Fertig", style: .done, target: self, action: #selector(doneTapped))
The problem is that googleButton and activityIndicator are not on the left/center:
What am I missing here?
Update:
I tried setting the leftBarButtonItem to a simple item with title and it works as expexted.. Why is it not working with the image?
I think it has to do with the intrinsicContentSize of the googleButton. Since you haven't explicitly set it, the size of the google logo image is expanding the width of the button. The intrinsicContentSize property of a UIButton has a set height by default, but none for the width:
let googleImage = UIImage(named: "google")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal).resizeTo(size: CGSize(width: 25, height: 25))
let googleButton = UIButton()
googleButton.setBackgroundImage(googleImage, for: .normal)
googleButton.addTarget(self, action: #selector(googleButtonTapped), for: .touchUpInside)
let googleBarButton = UIBarButtonItem(customView: googleButton)
You can create a UIImage extension to redraw the size of the google logo:
extension UIImage {
func resizeTo(size: CGSize) -> UIImage {
let renderer = UIGraphicsImageRenderer(size: size)
let image = renderer.image { _ in
self.draw(in: CGRect.init(origin: CGPoint.zero, size: size))
}
return image.withRenderingMode(self.renderingMode)
}
}
Change the button name to:
self.navigationItem.leftBarButtonItem = googleBarButton
Of course, the 25 points for the width and the height is arbitrary. Adjust it to fit your need.

How to fit an image in rightbarbuttonitem

I've been trying to put a hamburger button (the three parallel lines) to the right of the titleView in the nav bar, but every time I do, the image I put in covers the entire nav bar and gets rid of the image I have in titleView.
If I select a default image in the storyboard editor it will appear on the right side of the nav bar without any problems, but as soon as I select the hamburger button in the storyboard editor I get the same problem as before. I've tried with multiple different images and I've changed up the code a little bit with no success. Is there a way to resize the image I'm using so it will fit in the nav bar properly or is there just something wrong with my code?
Here is my code from viewController.swift below:
override func viewDidAppear(_ animated: Bool) {
let nav = self.navigationController?.navigationBar
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
imageView.contentMode = .scaleAspectFit
let titleImage = UIImage(named: "logowhitecircle")
imageView.image = titleImage
navigationItem.titleView = imageView
let menuButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
menuButton.contentMode = .scaleAspectFit
let menuImage = UIImage(named: "hamburgericon")
menuButton.setImage(menuImage, for: .normal)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: menuButton)
You need to set image size in the image assets like 3x = 84px, 2x=56px, 1x = 28px,
see the apple document for more info: https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/custom-icons/
let menuButton = UIBarButtonItem(image: UIImage(named: "logowhitecircle"), style: .plain, target: self, action: #selector(menuButtonTapped(_:)))
self.navigationItem.rightBarButtonItem = menuBu
tton
Try Using below code:
let imageBurger = UIImage(named: "hamburgericon")!
let btnLeftMenu = UIButton(type: .system)
btnLeftMenu.bounds = CGRect(x: 10, y: 0, width: imageBurger.size.width, height: imageBurger.size.height)
btnLeftMenu.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
btnLeftMenu.setImage(imageBurger, for: UIControl.State())
btnLeftMenu.setTitle(title, for: .normal)
let leftButton = UIBarButtonItem(customView: btnLeftMenu)
self.navigationItem.leftBarButtonItem = leftButton
Try this module FFBadgedBarButtonItem it's easy to use module, here is the documenataion Link
Below is my code how to implement it!
let image = UIImage(named: "yourImage")
let finalImage = resizeImage(image: image!, newWidth: 30)
navigationItem.rightBarButtonItem = FFBadgedBarButtonItem(image: finalImage, target: self, action: #selector(rightButtonTouched))
And here is the calling function
#objc func rightButtonTouched() {
// what event you need to perfom by clicking on this button
}
You need to create Bridging Header to work with this Obj-C module.
: D
Try this:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//create a new button
let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
//set image for button
button.setImage(UIImage(named: "hamburgericon"), forState: UIControlState.Normal)
//add function for button
button.addTarget(self, action: "customButtonPressed", forControlEvents: UIControlEvents.TouchUpInside)
//set frame
button.frame = CGRectMake(0, 0, 40, 40)
let barButton = UIBarButtonItem(customView: button)
//assign button to navigationbar
self.navigationItem.rightBarButtonItem = barButton
}
//This method will call when you press button.
func customButtonPressed() {
println("button pressed")
}
}

Adding a custom navigation bar covering content in screen

I have added a custom navigation bar via storyboard. I was expecting the content on the screen to automatically shift downward. but instead it completely covers content on the top of the screen.. is there a clean line of code that automatically creates that spacing between the navigation bar and the view itself?
You might have heard about Cocpods which i feel is a better way to go for cutsom Navigation bar.
You just need to implement the protocol and give the specifications you need for the Navigation bar
Go through the following cooped
https://cocoapods.org/pods/resizable-navigation-bar
Just call this method from viewDidLoad :
func createNavBar() {
let leftNavigationButton = UIButton()
leftNavigationButton.setImage(UIImage(named: "ic_back.png"), forState: .Normal)
leftNavigationButton.frame = CGRectMake(10, 10, 20, 15)
leftNavigationButton.addTarget(self, action: "onBackButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
let customBarItem = UIBarButtonItem(customView: leftNavigationButton)
self.navigationItem.leftBarButtonItem = customBarItem;
//set TitleAppIcon
let GR = UITapGestureRecognizer(target: self, action: Selector("headerLogoTapAction:"))
let imageView = UIImageView(frame: CGRect(x: 90, y: 0, width: ((UIScreen.mainScreen().bounds.width)/3), height: 40))
imageView.contentMode = .ScaleAspectFit
let image = UIImage(named: "yourimag.png") //or set title
imageView.image = image
imageView.addGestureRecognizer(GR)
imageView.userInteractionEnabled = true
navigationItem.titleView = imageView
}
Hope this gonna help you

Custom navigation bar image and text

I need in my app a custom navigation bar with an image and a text but I can't add the text.
Here is the code to add the image, how can I add the title?
let logo = #imageLiteral(resourceName: "navigationbaricon")
let imageView = UIImageView(image:logo)
self.navigationItem.titleView = imageView
Thanks
Where is the frame assigned for self.navigationItem.titleView? Set the frame for imageView and it will work.
You can wrap the UIImageView and the UILabel (which will hold the custom title) in an UIView and then assign the UIView to the self.navigationItem.titleView. Something like this:
let view = UIView(...);
let label = UILabel(...);
label.text = "Custom Title";
let image = UIImageView(image: UIImage(named: "..."));
view.addSubview(image);
view.addSubview(label);
self.navigationItem.titleView = view;
This one is worked for me
override func viewDidLoad() {
super.viewDidLoad()
let titleView = UIView()
titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
titleView.backgroundColor = UIColor.redColor()
let imageView = UIImageView(image: UIImage(named: "img")!)
imageView.frame = CGRectMake(0, 0, 40, 40)
imageView.contentMode = .ScaleAspectFill
titleView.addSubview(imageView)
self.navigationItem.titleView = titleView
}

Swift : Logo on navigation bar along with back button

I want to have the logo of my app followed by the app name on the navigation bar. Along with this, there should be a back button.
Below is a screenshot :
I've tried the code below.
self.navigationItem.setHidesBackButton(false, animated:true);
let imgLogo : UIImage = UIImage(named:"Logo")!
let imgViewLogo : UIImageView = UIImageView(image: imgLogo)
imgViewLogo.frame = CGRectMake(0, 0, 40, 40)
let leftItem:UIBarButtonItem = UIBarButtonItem(customView: imgViewLogo)
self.navigationItem.leftBarButtonItem = leftItem
// App Name set on storyboard at design-time
This places the logo on top of the back button shown below.
How can this be achieved?
You can use custom view for navigationItem.titleView. Create UIView with your logo and a label for UIViewController title and set
navigationItem.titleView = YOUR_CUSTOM_VIEW;
Instead of using .leftBarButtonItem use:
let imgLogo : UIImage = UIImage(named:"Logo")!
let imgViewLogo : UIImageView = UIImageView(image: imgLogo)
imgViewLogo.frame = CGRectMake(0, 0, 40, 40)
let leftItem:UIBarButtonItem = UIBarButtonItem(customView: imgViewLogo)
self.navigationItem.leftBarButtonItems?.append(leftItem)
It will be added along with the system back button
You can find tons of example about it.
In this example I've added also a space to centered well your logo if you needed:
let leftButton: UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "Logo")!, style: UIBarButtonItemStyle.Plain, target: self, action:#selector(MyViewController.leftButtonPress(_:)))
let negativeSpacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
negativeSpacer.width = -5.0 // Left inset to better center your logo
navigationItem.leftBarButtonItems = [negativeSpacer,leftButton]
func leftButtonPress(sender: AnyObject?) {
// do whatever you want when you press back button
}

Resources