Search code examples
swiftxcodeuibarbuttonitemrightbarbuttonitemnavigationitem

Navigation Bar Button Item Alignment Issue


I'm building a netflix clone. In configuring the nav bar, I keep running into an odd error that I can't seem to find a solution for anywhere: I want my nav bar to contain a "leftBarButtonItem" that houses a UIImage of the Netflix logo w a transparent background (located in my assets folder). But when I attempt to do this, the alignment is always off; as if padding is being added to either side of the image (see screenshots A & B below).

I've tried:

  • Replacing the UIImage with a title: String (see screenshots E & F below). Works as expected, but ideally want a UIImage here
  • Removing the line containing ".withRenderingMode"
  • Swapping out the image in my assets folder for smaller sizes
  • Changing the width of the UIImage, unsuccessfully (see screenshots C & D below)

For added context, you can follow the link below to my github repo. The problematic code is in Controllers > HomeViewController at line 33

Github Link: https://github.com/nlpope/Netflix-Clone

Failure Screenshots:

A) When UIImage is included:

B) UIImage result:

C) When width of -5 is added:

D) altered width result:

Partial-Success Screenshots:

E) when image is replaced w a title:

F) title result:


Solution

  • I got it; The issue was with the size of the netflix logo in the UIBarButtonItem. Before, I was directly assigning the netflix UIImage to navigationItem.leftBarButtonItem via the preset UIBarButtonItem(image:,style:,target:,action:),

    netflix clone Mk1

    instead I should have done this indirctly by passing a customView parameter:

    netflix clone Mk2

    This allowed me to set width and height constraints to the barButtonItem without the custom view (netflix logo) affecting it negatively (because it's just a custom view passed through what we're actually editing

    sources: Change size of UIBarButtonItem (image) in Swift 3