Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

safeAreaInsets for UIToolbar without using Constraints

I have an app that does all UI programmatically without using auto layout or any sort of constraints. At the bottom of the screen is a UIToolbar. I am trying to lay this out to play well with the iPhone X screen's bottom safe area but due to the design of the VCs I cannot use layout constraints.

So in my layoutSubviews callback I am doing this:

if (@available(iOS 11.0, *)) {
    toolbarHeight += UIApplication.sharedApplication.keyWindow.safeAreaInsets.bottom;
}

Then later setting the UIToolbar's frame directly with toolBarHeight.

This works in that the toolbar is now the correct height and adjusts when you rotate to landscape, but the problem is that the Toolbar's buttons are not top aligned, but rather centered vertically. I can't figure out how to set the contentInsets or some way to top align the UIToolbar buttons without using constraints.

Any ideas?

like image 593
Dave Haupert Avatar asked Nov 26 '17 09:11

Dave Haupert


People also ask

How do you get an inset safe area?

You obtain the safe area for a view by applying the insets in this property to the view's bounds rectangle. If the view is not currently installed in a view hierarchy, or is not yet visible onscreen, the edge insets in this property are 0 .

How do you add a safe area to a storyboard?

Select View Controller -> File Inspector (first tab) -> Use safe area layout guides (uncheck the checkbox). You can also change it programmatically in viewDidLoad(). Hope this Helps! Have you tried giving constraint through storyboard rather than programmatically?

How do I change the safe area in Xcode?

To use the new safe area, select Safe Area Layout Guides in the File inspector for the view controller, and then add constraints between your content and the new safe area anchors. This prevents your content from being obscured by top and bottom bars, and by the overscan region on tvOS.


1 Answers

UIToolbar will automatically fill the safe area. Keep the toolbar height as you would have (eg 49pts), and position it so that the bottom of the toolbar is at the top of the bottom safe area guide.

self.toolbar.width = self.view.width
self.toolbar.height = 49.0
self.toolbar.bottom = self.view.height - self.view.safeAreaInsets.bottom

The above code is using UIView+FrameAdjustments.

like image 180
Ric Santos Avatar answered Sep 22 '22 17:09

Ric Santos