Skip to content

Instantly share code, notes, and snippets.

@siberianisaev
Last active October 30, 2019 07:57
Show Gist options
  • Save siberianisaev/4fa28cb830d51d4b5803 to your computer and use it in GitHub Desktop.
Save siberianisaev/4fa28cb830d51d4b5803 to your computer and use it in GitHub Desktop.
Change height of UINavigationBar
import Foundation
private var AssociatedObjectHandle: UInt8 = 0
extension UINavigationBar {
var height: CGFloat {
get {
if let h = objc_getAssociatedObject(self, &AssociatedObjectHandle) as? CGFloat {
return h
}
return 0
}
set {
objc_setAssociatedObject(self, &AssociatedObjectHandle, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
}
override public func sizeThatFits(size: CGSize) -> CGSize {
if self.height > 0 {
return CGSizeMake(self.superview!.bounds.size.width, self.height);
}
return super.sizeThatFits(size)
}
}
@siberianisaev
Copy link
Author

@samuelbeek
Copy link

Thank you so much, really helped me out!

@degt
Copy link

degt commented Oct 22, 2015

Thanks!

To make it works with Xcode7 + swift 2.0 replace line 16 for this one:

objc_setAssociatedObject(self, &AssociatedObjectHandle, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)

@YHSX88
Copy link

YHSX88 commented Apr 8, 2016

Thanks siberianisaev and Degt, I got error when using 7.3 with 2.2 but all is good now thanks

@lgeefs
Copy link

lgeefs commented Jul 13, 2016

Thank you

@avaDeveloper
Copy link

where should call sizeThatFits method ?

@jasonwiener
Copy link

thanks a ton for this!

@jasonwiener
Copy link

@avaDeveloper, it's called internally by the navBar, you don't explicitly call it.

@felixdkatt
Copy link

when i use this my title view and buttons are off center closer to the bottom

@n8chur
Copy link

n8chur commented Jul 20, 2017

@felixdkatt you should be able to transform the view within sizeThatFits() to resolve this in iOS 10 and below:

self.transform = CGAffineTransformMakeTranslation(0, -(heightDelta));

But this hack appears to be broken in the iOS 11 beta and it doesn't look likely that it will be fixed according to this thread.

@hemangshah
Copy link

Please update it for the latest Swift.

@hilalbaig
Copy link

Thanks, here is its swift 3 version

@annjawn
Copy link

annjawn commented Dec 14, 2017

What is the usage for this? Where should I put the height?

@AlexanderBollbach
Copy link

what is the usage for this?

@bxem44
Copy link

bxem44 commented Oct 30, 2019

Dosen't work with iOS 13.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment