以编程方式相对于安全区域底部定位视图



我有一个从屏幕底部弹出的视图,并加载到我的应用程序委托中。我遇到的问题是我无法设置视图的 y 坐标,因此它将在所有屏幕尺寸上出现在相同的位置。就我而言,我正在尝试让此弹出视图显示在屏幕底部选项卡栏的正上方。

这是我的代码,我在其中放置相对于[[UIScreen mainScreen]边界的视图,但它在所有屏幕尺寸上都不一致。 如何获取所需的坐标,以便将此视图垂直放置在所有屏幕上的同一位置?

CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
float y = [UIScreen mainScreen].bounds.size.height;
UIInterfaceOrientation deviceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
if (UIInterfaceOrientationIsLandscape(deviceOrientation))
{
[UIView animateWithDuration:0.5
delay:.25
options: UIViewAnimationOptionCurveEaseOut
animations:^{
self->popcontroller.frame = CGRectMake(0,y -90, screenWidth, 40);
}
completion:^(BOOL finished){
}];
}
else{
[UIView animateWithDuration:0.5
delay:.25
options: UIViewAnimationOptionCurveEaseOut
animations:^{
self->popcontroller.frame = CGRectMake(0,y -120, screenWidth, 40);
}
completion:^(BOOL finished){
}];
}
brsAppDelegate *appDelegate = (brsAppDelegate *)[[UIApplication sharedApplication] delegate];
if (![[appDelegate window].subviews containsObject:popcontroller])
{  [[appDelegate window] addSubview:popcontroller];
[popcontroller setNeedsDisplay];
}
});

}

因此,为了检测边缘插图的额外间距,所有视图上都有一个称为safeAreaInsets的属性。这可用于检测是否需要向布局参数(顶部/底部或左侧/右侧(添加额外值。

因此,为了获得"额外边距",如果应用程序是纵向的,您可以检查该插图的顶部/底部值,如果应用程序是横向的,则可以检查插图的"左/右"值。

需要注意的一点是,默认情况下,此safeAreaInset是在控制器的根视图上设置的,因此,如果将自定义视图添加为子视图,则该自定义视图很可能不会正确设置此属性。

更具体地说,在您的情况下,"框架"代码看起来像

if deviceIsInPortrait {
let frame = CGRect(x:thisX,
y: -90 - self.view.safeAreaInsets.top // this will be 0 for non "notch" phones
width: myWidth
height: myHeight
}
else {
let frame = CGRect(x:thisX,
y: -90 - self.view.safeAreaInsets.left // this will be 0 for non "notch" phones
width: myWidth
height: myHeight
}

还有一条建议,尽可能多地使用自动布局。

最新更新