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

时间:2017-12-12 08:01:50

标签: ios objective-c ios11 xcode9 safearealayoutguide

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

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

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

请回答我的问题。!

1 个答案:

答案 0 :(得分:7)

以下是安全区域布局的示例代码。在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];

参考:Use Safe Area Layout programmatically

结果:

enter image description here