在iOS7.0以后,相對于ScrollView新增屬性,默認(rèn)為YES,系統(tǒng)會根據(jù)所在界面的astatus bar, search bar, navigation bar, toolbar, or tab bar等自動調(diào)整ScrollView的inset.
正是由于這一屬性,在添加ScrollView時(shí)會有意想不到的"驚喜".首先,調(diào)整ScrollView的inset, ScrollView的frame并沒有變化,而是其內(nèi)容的位置有變化,以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];
}
此時(shí)運(yùn)行結(jié)果如實(shí)例1,可以看到tableView的cell相對于tableView的根視圖向下調(diào)整了一個(gè)navigation bar的高度,而tableView的原點(diǎn)在左上角(透過navigation bar可以看到橙色);
實(shí)例1
同理,當(dāng)tableView.frame.origin.y的值不是0的時(shí)候,根據(jù)y值的不同,得到的視圖會有不同的效果.通過測試,當(dāng)tableView.frame.origin.y的大于0的時(shí)候,tableView的cell會相對的向下移動,反之亦然;
如果添加的ScrollView的高度比較小,甚至小于navigation bar的高度的時(shí)候, ScrollView添加到其根視圖了,但是其內(nèi)容只能顯示一部分甚至完全看不到不見,查看層級視圖的clipped content才發(fā)現(xiàn)內(nèi)容在ScrollView下面,這就是這個(gè)屬性的功勞.
但是要注意:這種自動調(diào)整是在ScrollView是其根視圖添加的的第一個(gè)控件的時(shí)候,才會出現(xiàn)自動調(diào)整的效果,如果在添加ScrollView之前添加了其他控件,不論控件的frame,自動調(diào)整都會失效.例如當(dāng)代碼如下時(shí)
- (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];
}
實(shí)例圖如下
總結(jié),automaticallyAdjustsScrollViewInsets屬性的自動調(diào)整,實(shí)際效果是調(diào)整ScrollView的內(nèi)容的y的值,而且當(dāng)ScrollView不是其根視圖添加的第一個(gè)控件的時(shí)候,這個(gè)屬性的修飾效果會"失效";
附官方文檔
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