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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With