简体   繁体   中英

UIScrollView contentInset not working

I'm having a problem with contentInset not working for a UIScrollView to work with a keyboard popup. It kind of works: for some reason I need large numbers (maybe above the view's height?) for it to do anything, despite all documentation of contentInset showing small numbers like 40.0 (eg for a bar), or the keyboard height.

I've reproduced the problem on a brand new application by the following steps:

  1. Create new single view application using Xcode new project
  2. On storyboard, drag in a scrollview, filling full view size
  3. On storyboard, drag in a button, at the very bottom of the screen (inside the scrollview)
  4. Link the scrollview to a new property in the ViewController
  5. Link button to a method in the ViewController
  6. Make the button's pressed method set the contentInset

Here is the code for the ViewController:

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@end

@implementation ViewController
- (IBAction)button:(id)sender {
    self.scrollView.contentInset = UIEdgeInsetsMake(0.0, 0.0, 600, 0.0);
}
@end

What am I missing / why do I need large numbers?

Check that self.scrollView.contentSize is set properly. If contentSize.height is 0 (as will be the case following your steps), then a large inset is required.

Try adding [self.scrollView setContentSize: CGSizeMake(320, 568)]; to the button method and you'll notice that your inset will now behave as expected.

Matt is right, it has to do with self.scrollView.contentSize . I'm using Auto Layout and the missing link for me was explicitly setting the scrollView's contentSize property to be the same as my contentView's frame size (contentView is the view inside my scrollView that holds all other views). My contentView is coded to have its size based on the elements I've placed within. They "push out" on the contentView and therefore dynamically drive the contentView's size. It's as a "last step" within viewDidLayoutSubviews that I link this dynamic size into scrollView.contentSize . Now things work as expected.

// Auto Layout Solution
- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.scrollView.contentSize = self.contentView.frame.size;
}

就我而言,我只是忘记在界面生成器中连接 ScrollView ......

I had the same issue when using auto layout with constraints. Scroll view refused to move with contentInset until I added the following line at the end of keyboardWillShow, then it all worked as expected. As stated above, I suspect that auto layout is resetting contentSize.

scrollView.contentSize = CGSize(width: scrollView.frame.width, height: scrollView.frame.height)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM