问题
I am trying to create a dynamic form using a UIScrollView, but I noticed when I used a NSLog
that my scrollView's contentSize.height = 0.00000
I built the scrollView to the width and height of the screen on storyboard with elements inside it. So why does it return 0? All the elements inside the scrollView are showing/functioning correctly. Does scrollView's contentSize always default at 0 and I just need to set it?
回答1:
Yes is 0 by default. You should set the content size of your scrollview by summing all the views height and the spaces between them, example:
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 60)];
scrollView.backgroundColor = [UIColor blueColor];
[self.view addSubview:scrollView];
NSUInteger spaceBetweenLabels = 10;
UILabel *firstLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 40)];
firstLabel.text = @"first label text";
UILabel *secondLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, spaceBetweenLabels + firstLabel.frame.size.height, 300, 40)];
secondLabel.text = @"second label text";
[scrollView addSubview:firstLabel];
[scrollView addSubview:secondLabel];
CGSize fullContentSize = CGSizeMake(300, firstLabel.frame.size.height + secondLabel.frame.size.height + spaceBetweenLabels);
[scrollView setContentSize:fullContentSize];
Of course if your scroll view height is higher than the content size height it won't scroll because everything is on the screen.
回答2:
Yes the content size for UIScrollView is 0 zero by default . In order to introduce scrolling into your scrollView , you need to set certain properties like setScrollEnabled , set Bouncing , set Horizontal/Vertical scrolling and the most important contentSize for the UIScrollView . A UIScrollView would not possess scrolling until unless the content size is greater than the Size of the UIScrollView .
回答3:
Try placing a UIView inside the ScrollView do not set any constraints on the UIView. Next place all your form controls inside the UIView and constrain them as normal.
Now the key is to set the last control on the form's bottom constraint to the UIView (ie bottom of the form) This will then translate thru Autolayout and not only will you have a height value but you will be able to vertically scroll your form. Also...
- Do not set the scrollView.contentSize
- Do not set translatesAutoresizingMaskIntoConstraints (leave as default)
- Do not set the height of the form (UIView) using constraints this is what Autolayout does
- Do not set any constraints on the form (UIView)
Note: If you want the width of your form (UIView) to be the same as your devices... then right click on the form (UIView) in the navigation bar (i.e. where all the controls are listed in the tree style) and then drag it to the main top UIView element. Then in the popup select equal widths
来源:https://stackoverflow.com/questions/16321178/uiscrollview-contentsize-height-is-0-0000-by-default