告别 automaticallyAdjustsScrollViewInsets,拥抱 contentInsetAdjustmentBehavior
2024-01-20 12:34:58
iOS 11 适配指南
苹果在 iOS 11 中废弃了 UIViewController 的 automaticallyAdjustsScrollViewInsets 属性,改用 UIScrollView 的 contentInsetAdjustmentBehavior 属性来替换它。automaticallyAdjustsScrollViewInsets 属性用于自动调整滚动视图的内边距,以避免内容被导航栏、工具栏和标签栏遮挡。contentInsetAdjustmentBehavior 属性提供了更细粒度的控制,可以指定滚动视图在不同情况下如何调整内边距。
contentInsetAdjustmentBehavior 属性的用法
contentInsetAdjustmentBehavior 属性有三个可能的值:
- automatic :滚动视图的内边距将根据当前的上下文自动调整。
- scrollableAxes :滚动视图的内边距将根据滚动方向自动调整。
- never :滚动视图的内边距不会自动调整。
在大多数情况下,使用 automatic 值即可。但是,在某些情况下,您可能需要使用其他值。例如,如果您希望滚动视图的内边距始终保持不变,则可以使用 never 值。
解决键盘上推问题
在 iOS 11 中,使用 UIScrollView 时可能会遇到键盘上推问题。这是因为 contentInsetAdjustmentBehavior 属性的默认值为 automatic,这会导致滚动视图在键盘弹出时自动调整内边距。这可能会导致滚动视图的内容被键盘遮挡。
要解决这个问题,您可以将 contentInsetAdjustmentBehavior 属性设置为 scrollableAxes 或 never。这样,滚动视图的内边距就不会在键盘弹出时自动调整,从而避免内容被键盘遮挡。
示例代码
以下代码示例演示了如何在代码中使用 contentInsetAdjustmentBehavior 属性:
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentBehaviorScrollableAxes;
注意
- 在 iOS 11 中,如果您使用的是 UITableView,则需要将 UITableView 的 estimatedRowHeight 属性设置为 0。否则,UITableView 的高度可能会计算错误。
- 在 iOS 11 中,如果您使用的是 UICollectionView,则需要将 UICollectionView 的 estimatedItemSize 属性设置为 CGSizeZero。否则,UICollectionView 的高度可能会计算错误。
结论
contentInsetAdjustmentBehavior 属性是一个非常有用的属性,可以帮助您控制滚动视图的内边距。通过正确使用这个属性,您可以避免键盘上推问题,并确保您的滚动视图的内容始终可见。