Why won't basic UIScrollView with a few button

2019-07-21 11:56发布

问题:

Why won't basic UIScrollView with a few buttons scroll?

So all I have done is:

  • Create a view based iPhone app
  • drag in a UIScrollView into the main controller xib file
  • the scrollview now sits as a child of View in IB
  • in IB in scrollview increase it's view height up to 1000
  • add some buttons to the scroll view (so they appear as children of the scroll view)
  • did create the instance variable also, and property IBOutlet, synthesize
  • linked in IB the File Owner scrollView outlet to the scroll view
  • checked to ensure the scroll view in IB had the attribute "scrolling enabled" ticked

But still after all this in the iPhone simulator it won't let me scroll the view?

回答1:

Only one more thing you have to do: set the contentSize property on your scroll view to an appropriate value:

[scrollView setContentSize:CGSizeMake(
   scrollView.bounds.size.width,
   CGRectGetMaxY(bottommostSubview.frame)
)];

Where bottommostSubview is an outlet connected to the subview of the scrollview that’s closest to the bottom. You could also write a method to find this view automatically, or just hard-code a value if you know the size will never change.

The default contentSize is CGSizeZero which effectively disables scrolling.



回答2:

You probably don't want to change your scrollviews frame.size.height property to 1000.0, but your scrollviews contentSize.height.



回答3:

No, the correct answer is:

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [self.scrollView setContentSize:CGSizeMake(320, 1700)];  
}

The original answer I founded on next link:

UIScrollView won't scroll (Storyboards) -> Find Evana's answer

I waste a lot of time trying implement scroll (and repeatedly). I have even used 2 views (UIScrollView and UIView inside the first)

It is not necessary!

THE KEY IS: viewDidLayoutSubviews

In the storyboard you implement UIScrollView as any other element,

but the key is setContentSize in method viewDidLayoutSubviews