【问题标题】:Position a view relative to the bottom of the safe area programmatically以编程方式相对于安全区域的底部定位视图
【发布时间】:2018-09-30 21:20:05
【问题描述】:

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

这是我的代码,我将视图相对于 [[UIScreen mainScreen] bounds] 放置,但它在所有屏幕尺寸上并不一致。我怎样才能获得我需要的坐标,以便我可以将此视图垂直放置在所有屏幕上的同一位置?

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

}

【问题讨论】:

    标签: ios xcode autolayout safearealayoutguide


    【解决方案1】:

    所以为了检测边缘插入的额外间距,所有视图都有一个名为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
    }
    

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

    【讨论】:

    • 谢谢! safeAreaInserts 正是我所需要的,您的示例对我非常有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 2012-01-05
    • 1970-01-01
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多