Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the height of UIToolbar in iOS 7

I am trying to change the height of my UIToolbar in a new iOS 7 project but I am not able to.

I am using a UINavigationController to manage a couple of UIViewController. I tried setting the frame for the toolbar via the navigation controller but alas, the toolbar property is read-only.

I looked at "Is there a way to change the height of a UIToolbar?" but that did not work.

I tried subclassing UIToolbar, forcing a custom height and setting the right class in the Storyboard but that did not work neither, height keeps on being 44px.

I thought about auto-layout could not set any constraint on the size of the toolbar, every field is disabled.

I can set a custom view in a UIBarButtonItem with a bigger height than the toolbar. The big item will be correctly rendered but it will overflow from the toolbar.

This is the best I could do: screenshot

Is it actually possible to change the height of the UIToolbar in iOS 7? Or am I supposed to create a bunch of custom items to mimic it?

like image 255
Fabien Freling Avatar asked Oct 05 '13 10:10

Fabien Freling


4 Answers

Following the @Antoine suggestion using sizeThatFits, here is my Toolbar subclass with an height of 64:

import UIKit

class Toolbar: UIToolbar {
    override func layoutSubviews() {
        super.layoutSubviews()
        frame.size.height = 64
    }

    override func sizeThatFits(size: CGSize) -> CGSize {
        var size = super.sizeThatFits(size)
        size.height = 64
        return size
    }
}

Then, when initializing the navigation controller, I say it should use that class:

let navigationController = UINavigationController(navigationBarClass: nil, toolbarClass: Toolbar.self)
like image 150
gpbl Avatar answered Sep 27 '22 20:09

gpbl


The easiest way I found to set the toolbar height was to use a height constraint as follows:

let toolbarCustomHeight: CGFloat = 64

toolbar.heightAnchor.constraintEqualToConstant(toolbarCustomHeight).active = true
like image 32
shawnynicole Avatar answered Sep 27 '22 20:09

shawnynicole


I've fixed this by subclassing UIToolbar and pasting the following code:

override func layoutSubviews() {
    super.layoutSubviews()

    var frame = self.bounds
    frame.size.height = 52
    self.frame = frame
}

override func sizeThatFits(size: CGSize) -> CGSize {
    var size = super.sizeThatFits(size)
    size.height = 52
    return size
}
like image 26
Antoine Avatar answered Sep 27 '22 22:09

Antoine


If you are using same height for all screens, this should do the trick

extension UIToolbar {
    open override func sizeThatFits(_ size: CGSize) -> CGSize {
        return CGSize(width: UIScreen.main.bounds.width, height: 60)
    }
}
like image 38
artuc Avatar answered Sep 27 '22 22:09

artuc