如何以编程方式添加安全区域

How to add a safe area programmatically

当您打开视图时,它将如下图所示,

i Phone x open view

i Phone 8 open view

对于iphone x,我想在当前视图中以编程方式添加一个安全区域。

尝试的来源如下

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

我想应用这个资源,但我不知道该怎么做。

请回答我的问题!

这是安全区域布局的示例代码。在 Objective-C 试试看:

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];

参考自:

结果: