8

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.!

Krunal
  • 77,632
  • 48
  • 245
  • 261
Nam
  • 163
  • 1
  • 1
  • 8
  • This source seems to be applicable too. UIWindow *window = UIApplication.sharedApplication.keyWindow; CGFloat topPadding = window.safeAreaInsets.top; CGFloat bottomPadding = window.safeAreaInsets.bottom; – Nam Dec 12 '17 at 08:06

1 Answers1

10

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

Krunal
  • 77,632
  • 48
  • 245
  • 261
  • 1
    myView.translatesAutoresizingMaskIntoConstraints = NO; If you use this source, the screen will be completely garbled. – Nam Dec 12 '17 at 08:15
  • @Nam - I've tried this code practically and here is its result (a red view). It working fine for me. – Krunal Dec 12 '17 at 08:23
  • @Krunal Instead of reposting your answer over and over, you should vote to close the question as a duplicate. – rmaddy Dec 12 '17 at 15:08