UIScrollView顶部留有64的空白

今天在使用UIScrollView时,在scrollView里添加了控件。明明添加的控件的frame的y值设置的是0,但是添加的控件总是往下偏移64 。后经过查阅资料发现,原来是automaticallyAdjustsScrollViewInsets这个属性的问题。

我们来看看苹果的官方文档是如何描述这个属性的:

A Boolean value that indicates whether the view controller should automatically adjust its scroll view insets.
一个布尔值,指示视图控制器是否应自动调整其滚动视图插图。

The default value of this property is YES, which lets container view controllers know that they should adjust the scroll view insets of this view controller’s view to account for screen areas consumed by a status bar, search bar, navigation bar, toolbar, or tab bar. Set this property to NO if your view controller implementation manages its own scroll view inset adjustments.
此属性的默认值为YES,这使得容器视图控制器知道他们应该调整视图控制器视图的滚动视图插入来考虑状态栏,搜索栏,导航栏,工具栏或标签栏所占用的屏幕区域 。 如果您的视图控制器实现管理其自己的滚动视图,则将此属性设置为NO。

当我们使用ScrollView时,系统会流出64的留白来容纳状态栏,搜索栏,导航栏,工具栏或标签栏。

我们通过一个demo来解释这个问题。

scrollViewBug

我们创建一个新的项目,给ViewController绑上一个NavigationController,绑定方法如下图所示

给ViewController绑定一个NavigationController

// ViewController.m
#import "ViewController.h"

#define screen_w [UIScreen mainScreen].bounds.size.width
#define screen_h [UIScreen mainScreen].bounds.size.height


@interface ViewController ()

@property (nonatomic,strong) UIScrollView *scrollView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.title = @"scrollViewBug";

    // 设置scrollView
    [self setupScrollView];

    // 测试
    [self test];

    // 在iOS7之后,导航控制器中scrollView顶部会添加64的额外滚动区域
    self.automaticallyAdjustsScrollViewInsets = NO;
}

- (void)test
{
    _scrollView.contentSize = CGSizeMake(screen_w * 2, 0);

    //测试用view
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(screen_w, 0, screen_w, screen_h - 64)];
    view.backgroundColor = [UIColor blueColor];
    [_scrollView addSubview:view];
}

- (void)setupScrollView
{
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, screen_w, screen_h - 64)];
    scrollView.backgroundColor = [UIColor redColor];
    [self.view addSubview:scrollView];

    _scrollView = scrollView;
}

如下图所示,我们将automaticallyAdjustsScrollViewInsets属性的值设置为NO,即可解决问题。

解决scrollView顶部留白问题

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值