Matt Miszewski Matt Miszewski - 1 month ago 9
iOS Question

UIImageView not positioning correctly in Navbar and Status Bar

I am trying to use an Image in my Navigation Bar. Keep getting close but no cigar. With the code below, it loads the image fine and positions it nearly correct. It appears to have a pad around the view, but I have no constraints around it. When I remove the Status bar it shrinks the image but positions it fine within the NavBar.

let nav = self.navigationController?.navigationBar

for parent in self.navigationController!.navigationBar.subviews {
for childView in parent.subviews {
if(childView is UIImageView) {
childView.removeFromSuperview()
}
}
}

nav?.barStyle = UIBarStyle.Default
nav?.tintColor = UIColor.blueColor()

let app = UIApplication.sharedApplication()
let SBheight = app.statusBarFrame.size.height
let totalheight = SBheight + nav!.frame.height
let totalwidth = nav!.frame.width
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: totalwidth , height: totalheight))
imageView.clipsToBounds = true
imageView.contentMode = .ScaleAspectFill

var image = UIImage(named: "HRC")
imageView.image = image

navigationItem.titleView = imageView


Here is the shot of the NavBar Area:

Nav Image Not Placing Correctly.

Answer

I can set the background picture of a navigation bar with no issue with the code below.

Swift 3.0

let backgroundImage = UIImage(named: "name_of_background_image")?.resizableImage(withCapInsets: UIEdgeInsetsMake(0, 0, 0, 0), resizingMode: .stretch)
self.navigationController?.navigationBar.setBackgroundImage(backgroundImage, for: .default)

Swift 2.3

let backgroundImage = UIImage(named: "name_of_background_image")?.resizableImageWithCapInsets(UIEdgeInsetsMake(0, 0, 0, 0), resizingMode: .Stretch)
self.navigationController?.navigationBar.setBackgroundImage(backgroundImage, forBarMetrics: .Default)

You can add the code above to viewDidLoad, and customize the background image for each viewController.

Make sure you render the image as Original from the asset catalog.

enter image description here

And double check if your image has the right size.

@2x -> 750 x 128

@3x -> 1125 x 192

Comments