Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a safe area programmatically

When you open the view, it will look like the image below,

i Phone x open view

i Phone 8 open view

For iphone x, I would like to add a safe area programmatically in the current view.

The source to try is as follows.

UIView *view = self.view;

if (@available(iOS 11.0, *)) {
    UILayoutGuide * guide = view.safeAreaLayoutGuide;
    [view.topAnchor constraintEqualToAnchor:guide.topAnchor].active = YES;
    [view.bottomAnchor constraintEqualToAnchor:guide.bottomAnchor].active = YES;
}

I suppose to apply this source, but I do not know what to do.

please answer about my question.!

like image 562
Nam Avatar asked Dec 12 '17 08:12

Nam


People also ask

How do I add a 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.

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 .

What is safe area guide?

The safe area layout guide is a property of the UIView class and it inherits from the UILayoutGuide class. It was introduced in iOS 11 and tvOS 11. It helps you correctly position views in a layout. The safe area layout guide replaces the top and bottom layout guides of the UIViewController class.

Does safe area include navigation bar?

With ios16 the navigation bar appears onto of the status bar (in the safe area), the tab bar is also in the safe area.


1 Answers

Here is sample code for Safe Area Layout. Try this in Objective-C and see:

UIView * myView = // initialize view using IBOutlet or programtically

myView.backgroundColor = [UIColor red];
myView.translatesAutoresizingMaskIntoConstraints = NO;

UILayoutGuide * guide = self.view.safeAreaLayoutGuide;
[self.myView.leadingAnchor constraintEqualToAnchor:guide.leadingAnchor].active = YES;
[self.myView.trailingAnchor constraintEqualToAnchor:guide.trailingAnchor].active = YES;
[self.myView.topAnchor constraintEqualToAnchor:guide.topAnchor].active = YES;
[self.myView.bottomAnchor constraintEqualToAnchor:guide.bottomAnchor].active = YES;

// Refresh myView and/or main view
[self.view layoutIfNeeded];
//[self.myView layoutIfNeeded];

Ref from: Use Safe Area Layout programmatically

Result:

enter image description here

like image 147
Krunal Avatar answered Sep 30 '22 19:09

Krunal