Questions regarding this issues has been asked. I tried everything and couldn't fix my problem. I struggled for 2 hours and now i am posting this here.
Issue: UIScrollView's top contentInset has always 20px extra space.
I have viewcontroller xib, not storyboard.
First, related question and its solution on stackoverflow assumes that UIScrollView is the root view of UIViewController. But my scrollview is not root view and hence that why maybe
self.automaticallyAdjustsScrollViewInsets = NO;
is not working
Here is the screenshot of that extra 20 px top inset. Extra 20px is the black area between white line and light gray content of UIScrollView I am unable to get this fixed.
Am i doing something wrong? Autolayout constraints seems fine.
Do you have your controller embedded in a navigationController? It seems that iOS is leaving 20px at the top for a status bar but your controller doesn´t have one.
Either way, in your viewDidLoad it should work if you adjust the scrollView before calling super:
- (void)viewDidLoad {
self.automaticallyAdjustsScrollViewInsets = NO;
self.scrollView.contentInset = UIEdgeInsetsMake(0,0,0,0);
[super viewDidLoad];
}
The reason why iOS might be automatically forcing your scrollView to have a 20px TOP contentInset is because it might be the view with index 0 in your main view. You can read further here: http://b2cloud.com.au/how-to-guides/uiviewcontroller-changes-in-ios7
By default, a UIViewController will automatically adjust the content insets of it’s UIScrollView (including UITableViews) at view index 0, the very back. This means if there’s a button, label, or any other view behind your table view, you wont get this behaviour for free.
Here the accepted answer of Pauls in SWIFT 4:
override func viewDidLoad() {
backGroundScrollView.contentInsetAdjustmentBehavior = .never
backGroundScrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
super.viewDidLoad()
}
For iOS 11.1 and later:
Swift 5
if #available(iOS 11.1, *) {
self.tableView.verticalScrollIndicatorInsets.top = CGFloat.leastNonzeroMagnitude
}
ObjC
if (@available(iOS 11.1, *)) {
self.tableView.verticalScrollIndicatorInsets = UIEdgeInsetsMake(__DBL_MIN__, 0, 0, 0);
}
Reason why I'm not using 0
, but CGFloat.leastNonzeroMagnitude
is that in some cases iOS applies default value, when value is set to 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With