contentInset的深度分析
OC 日常笔记碎片知识
- 1-分析ScrollView系统什么时候调整内边距?
ViewController添加3个ScrollView,每个ScrollView添加开一个swich.

1.通过观察发现并没有修改内边距.
- 2-思考:如果添加了导航控制器呢?

2.橙色ScrollView内边距发生变化, 默认首个控件会调整内边距.
- 3-思考:如果不是首个控件呢?

首个控件不是ScrollView,系统不会调整内边距.
- 4-如何解决额外增加的属性
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 不要自动调整scrollView的内边距
//方法一
// self.automaticallyAdjustsScrollViewInsets = NO;
//方法二
self.scrollView.contentInset = UIEdgeInsetsMake(-64, 0, 0, 0);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSLog(@"%@", NSStringFromUIEdgeInsets(self.scrollView.contentInset));
}
@end

- 5-思考:苹果为什么增加额外内边距?

为了不被导航控制器挡住可视控件.
研究TableView的ContentInset
*代码演示:
#import "TestTableViewController.h"
@interface TestTableViewController ()
@end
@implementation TestTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
// self.automaticallyAdjustsScrollViewInsets = NO;
// self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 30;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 1.确定重用标示:
static NSString *ID = @"cell";
// 2.从缓存池中取
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
// 3.如果空就手动创建
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
cell.backgroundColor = [UIColor redColor];
}
cell.textLabel.text = [NSString stringWithFormat:@"%zd", indexPath.row];
return cell;
}
//点击每行cell打印contentInset
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"%@", NSStringFromUIEdgeInsets(tableView.contentInset));
}
@end
- 1-无导航栏演示:

- 2-有导航栏与TabBar

通过添加导航栏与TabBar观察发现有穿透效果.
-
3-官方文档解释
分析.png
这个属性默认是YES,允许控制器调整内部的内边距,当scrollView有状态栏,导航栏, tabBar就会调整内边距.如何设置为NO,就手动调整.
- 4-历史
设置tableView的背景颜色
从IOS7开始有穿透效果,是由内边距造成.
从iOS7开始,默认情况下控制器的View占据正个屏幕.tableView的内容有很多cell, 非常长.还可以往上移动,当穿过导航栏就有穿透效果,超出父控件, Y值越大. 超出离开屏幕看不见被循环利用.
iOS7以前, 整个tableView不会填充屏幕, 假如屏幕高度480 , 会480 - 64 = 416. 那么屏幕高度是416.
内容显示上去是不会调整内边距,没有穿透效果.
- 5-总结:
contentInset的调整
默认情况下, 如果一个控制器A处在导航控制器管理中, 并且控制器A的第一个子控件是UIScrollView, 那么就会自动调整这个UIScrollView的contentInsetUIEdgeInsetsMake(64, 0, 0, 0) // 有导航栏
UIEdgeInsetsMake(20, 0, 0, 0) // 没有导航栏
默认情况下, 如果一个控制器A处在导航控制器管理中, 并且导航控制器又处在UITabBarController管理中, 并且控制器A的第一个子控件是UIScrollView, 那么就会自动调整这个UIScrollView的contentInsetUIEdgeInsetsMake(64, 0, 49, 0)
如何禁止上述的默认问题?
控制器A.automaticallyAdjustsScrollViewInsets = NO;