Navbar’s titleview meets button: UINavigationbar

After dealing with some problems to add a single button as titleview of a UINavigationbar I decided to provide a small component to handle this scenario. There are several examples available showing how to add a segmented control in the center of a navigation bar, but as a segmented control has to contain at least two segments a single button could not get covered with that approach.

One could think a UIBarButtonItem would be the right choice to add a single button to a navigation bar. Setting left or right navigation bar buttons works fine that way, but not with the title view. As UIBarButtonItem is not a subclass of UIView, you can’t set it as title view. Therefore I prepared a UIButton to look like a UIBarButtonItem such that you can use it in three different ways:

  • with an icon: The button displays an icon and fits to the icon’s size
  • with a title: The button displays a title and fits to the text’s size
  • with a fixed width: The button has a given width, but no initial content

The class UINavbarButton is a subclass of UIButton without any further methods but the constructors:

The button can be used like in the following example:

The button gets allocated and initialized with an image and a selector that is called when the button gets pressed. The style attribute defines if the button is black or gray. The value can be read from the related navigation bar. After that the button instance gets assigned as title view of the main view’s navigation item and gets released. To get the example working “UINavbarButton.h” got imported before.

You find the component and a simple example app that shows all three kinds of usage for black and default navigation bar style in this xcode project: NavbarButton Xcode Project

To use the button in your project just drag and drop the group “NavbarButton Sources” in your source tree.

Posted in Code Snippets.

Leave a Reply

Your email address will not be published. Required fields are marked *