contentInsetAdjustmentBehavior详解

7,547 阅读2分钟

在IOS11以后的系统中,由于苹果手机多了一个刘海,对于UIScrollView及其子类控件的屏幕适配,便多了一份需留意的点,趁今天有空,回顾和整理一下scrollView里contentInsetAdjustmentBehavior这个属性。

拿捏:

先看下contentInsetAdjustmentBehavior到底是个啥

枚举定义是这样的:

typedef NS_ENUM(NSInteger, UIScrollViewContentInsetAdjustmentBehavior) {
    UIScrollViewContentInsetAdjustmentAutomatic,
    UIScrollViewContentInsetAdjustmentScrollableAxes,
    UIScrollViewContentInsetAdjustmentNever,
    UIScrollViewContentInsetAdjustmentAlways, 
}

Automatic:自动判断需不需要适配安全区域,当controller的automaticallyAdjustsScrollViewInsets = YES时,会适配安全区域,NO的时候,就不会适配安全区域。

ScrollableAxes:这个稍微难理解,当contentSize.width/height > frame.size.width/height的时候,或者,scrollView.alwaysBounceHorizontal/Vertical = YES的时候,适配安全距离。

Never:完全不适配安全区域。

Always:不管啥情况下,都适配安全区域。

来个例子:

//创建一个scrollView,添加一个图片
self.view.backgroundColor = [UIColor whiteColor];
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame: self.view.bounds];
scrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
UIImage *testImg = [UIImage imageNamed: @"img"];
UIImageView *imageView = [[UIImageView alloc] initWithImage: testImg];
[self.view addSubview: scrollView];

一、UIScrollViewContentInsetAdjustmentAutomatic

自动调整是否需要适配安全距离

CGRect frame = imageView.frame;
frame.size.width = 390;
frame.size.height = 588;
imageView.frame = frame;
    
[scrollView addSubview: imageView];
scrollView.contentSize = imageView.frame.size;
scrollView.contentInsetAdjustmentBehavior =  UIScrollViewContentInsetAdjustmentAutomatic;

当:controller的automaticallyAdjustsScrollViewInsets = YES的时候,适配安全区域: 但我们发现在横屏状态下刘海屏没有适配,看来Automatic也没那么Automatic = =

来个配置:

scrollView.alwaysBounceHorizontal = YES; 解决! 当:controller的automaticallyAdjustsScrollViewInsets = NO的时候,不适配安全区域

二、UIScrollViewContentInsetAdjustmentScrollableAxes

这种模式下有几种情况

情况一:scrollView的ContentSize很小,则不适配安全区域。

情况二:scrollView的ContentSize很小,但alwaysBounceHorizontal = YES ,alwaysBounceVertical = YES,则适配安全区域。

情况三:scrollView的ContentSize大于超出显示范围,则适配安全区域。

图片就不贴了,挺好理解的。

另外的俩模式UIScrollViewContentInsetAdjustmentNeverUIScrollViewcontentInsetAdjustmentAlways也不讲了都是字面意思。

最后附一个demo帮助理解