在iOS7.0以后,相對于ScrollView新增屬性,默認為YES,系統會根據所在界面的astatus bar, search bar, navigation bar, toolbar, or tab bar等自動調整ScrollView的inset.
正是由于這一屬性,在添加ScrollView時會有意想不到的"驚喜".首先,調整ScrollView的inset, ScrollView的frame并沒有變化,而是其內容的位置有變化,以UITableView為例(演示方便),代碼如下
- (void)viewDidLoad {
[super viewDidLoad];
UITableView *tableView = [[UITableView alloc]initWithFrame:self.view.bounds];
tableView.backgroundColor = [UIColor orangeColor];
tableView.dataSource = self;
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellid"];
[self.view addSubview:tableView];
}
此時運行結果如實例1,可以看到tableView的cell相對于tableView的根視圖向下調整了一個navigation bar的高度,而tableView的原點在左上角(透過navigation bar可以看到橙色);
實例1
同理,當tableView.frame.origin.y的值不是0的時候,根據y值的不同,得到的視圖會有不同的效果.通過測試,當tableView.frame.origin.y的大于0的時候,tableView的cell會相對的向下移動,反之亦然;
如果添加的ScrollView的高度比較小,甚至小于navigation bar的高度的時候, ScrollView添加到其根視圖了,但是其內容只能顯示一部分甚至完全看不到不見,查看層級視圖的clipped content才發現內容在ScrollView下面,這就是這個屬性的功勞.
但是要注意:這種自動調整是在ScrollView是其根視圖添加的的第一個控件的時候,才會出現自動調整的效果,如果在添加ScrollView之前添加了其他控件,不論控件的frame,自動調整都會失效.例如當代碼如下時
- (void)viewDidLoad {
[super viewDidLoad];
//添加tableView
UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,100, self.view.bounds.size.width, self.view.bounds.size.height)];
tableView.backgroundColor = [UIColor orangeColor];
tableView.dataSource = self;
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellid"];
//添加label
UILabel *label = [UILabel labelWithText:@"label" andTextColor:[UIColor darkGrayColor] andFontSize:18];
[label sizeToFit];
label.frame = CGRectMake(0, 0, label.bounds.size.width, label.bounds.size.height);
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0,100, self.view.bounds.size.width, self.view.bounds.size.height)];
view.backgroundColor = [UIColor greenColor];
[view addSubview:label];
[view addSubview:tableView];
[self.view addSubview:view];
}
實例圖如下
總結,automaticallyAdjustsScrollViewInsets屬性的自動調整,實際效果是調整ScrollView的內容的y的值,而且當ScrollView不是其根視圖添加的第一個控件的時候,這個屬性的修飾效果會"失效";
附官方文檔
A Boolean value that indicates whether the view controller should automatically adjust its scroll view insets.
Discussion
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.
Availability
Available in iOS 7.0 and deprecated in iOS 11.0