Search code examples
iosuitoolbar

Programmatically create UIToolbar with default height


There are a number of questions regarding the height of UIToolbar, but I don't see one where the height is obtained dynamically. Is there a way to create a UIToolbar with the correct default height?


Solution

  • Create the toolbar with 0 height, then call sizeToFit. The toolbar will then have the default height.

    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, width, 0)];
    [toolbar sizeToFit];
    

    Swift version:

    let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: width, height: 0))
    toolbar.sizeToFit()