Changing the height of UIToolbar in iOS 7

一笑奈何 提交于 2019-12-05 02:01:06

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)

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

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
}

Although many solutions point in the right direction, they have either some layout issues or doesn't work properly. So, here's my solution:

Swift 3, custom UIToolbar subclass

class Toolbar: UIToolbar {

    let height: CGFloat = 64

    override func layoutSubviews() {
        super.layoutSubviews()

        var newBounds = self.bounds
        newBounds.size.height = height
        self.bounds = newBounds
    }

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

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)
    }
}

You can customize the height of your UIToolbar in iOS 7 with the following code. I have it tested and working in my current project.

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    // Make the Toolbar visible with this line OR check the "Shows Toolbar" option of your Navigation Controller in the Storyboard
    [self.navigationController setToolbarHidden:NO];

    CGFloat customToolbarHeight = 60;
    [self.navigationController.toolbar setFrame:CGRectMake(0, self.view.frame.size.height - customToolbarHeight, self.view.frame.size.width, customToolbarHeight)];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!