I am struggling with UIScrollView
content margins.
Basically what I am trying to achieve is presenting some content in a scrollview shown inside a modal view.
But I am facing an issue on the iPhones with notch when the content is big enough to require scrolling. When that’s the case the scrollview.adjustedContentInset
takes account of the safe areas. When it doesn’t require scrolling, the content insets remains zero.
I need that behaviour to be more consistent, is there a way to force using the safe areas or to prevent adjusting the content inset?
I tested it in a blank projet and reproduced the issue, basically I have two ViewControllers
, one that presents the second and the second that dynamically creates a height constraint to a child view to make the content scrollable.
(I made a close button that remains at the center of the screen)
You can see the top margin is different depending on the height of the content.
After some research, I have found a property on UIScrollView
made explicitly for that purpose: contentInsetAdjustmentBehavior
.
It’s an enum of type UIScrollView.ContentInsetAdjustmentBehavior
and it can be one of the four values: automatic
, scrollableAxes
, never
and always
.
I fixed the issue by using
override func viewDidLoad() {
super.viewDidLoad()
scrollView.contentInsetAdjustmentBehavior = .always
}
Now the safe area is always present.