目标C:如何以编程方式在安全区域内创buildself.view
我刚刚改变了我的应用程序从支持iOS 8,并支持iOS 9和以上。
由于我不使用故事板创build我的意见,我想知道是否有“使用安全区指南”选项编程或类似的东西。
我试图锚定我的观点,但他们保持重叠在iPhone X模拟器的顶部和底部。
在Objective-C中试试这个,看看:
UIView * myView = // initialize view using IBOutlet or programtically myView.backgroundColor = [UIColor redColor]; myView.translatesAutoresizingMaskIntoConstraints = NO; if (@available(iOS 11, *)) { UILayoutGuide * guide = self.view.safeAreaLayoutGuide; [myView.leadingAnchor constraintEqualToAnchor:guide.leadingAnchor].active = YES; [myView.trailingAnchor constraintEqualToAnchor:guide.trailingAnchor].active = YES; [myView.topAnchor constraintEqualToAnchor:guide.topAnchor].active = YES; [myView.bottomAnchor constraintEqualToAnchor:guide.bottomAnchor].active = YES; } else { UILayoutGuide *margins = self.view.layoutMarginsGuide; [myView.leadingAnchor constraintEqualToAnchor:margins.leadingAnchor].active = YES; [myView.trailingAnchor constraintEqualToAnchor:margins.trailingAnchor].active = YES; [myView.topAnchor constraintEqualToAnchor:self.topLayoutGuide.bottomAnchor].active = YES; [myView.bottomAnchor constraintEqualToAnchor:self.bottomLayoutGuide.topAnchor].active = YES; } // Refresh myView and/or main view [self.view layoutIfNeeded]; //[self.myView layoutIfNeeded];
请参阅:以编程方式使用安全区域布局
结果:
您可以编程方式查找顶部和底部填充。 我认为这将解决您的问题。
if (@available(iOS 11.0, *)) { UIWindow *window = UIApplication.sharedApplication.keyWindow; CGFloat topPadding = window.safeAreaInsets.top; CGFloat bottomPadding = window.safeAreaInsets.bottom; }