Claudia Laurie Claudia Laurie - 3 months ago 5x
Swift Question

swift Xcode having issues with CGRect frame sizing for contents in scrollView

I have a few elements that I want to lay out in a scrollView vertically with one element below the other. I have a UILabel, a UITextView, a UIImageView, another UITextView, followed by another UITextView (in the scrollView I want there to be a header, an intro paragraph, an image, a body paragraph, and a conclusion paragraph. I can't hard code the sizes of these elements because there are different dictionaries and images for different pages. How can I appropriately find the CGRect make float sizes for the frame of each view element? I am particularly having issues with the Y values.

This is the code that I have:

let startingY = (self.navigationController?.navigationBar.frame.height)! +

//Position subViews on screen.
self.categoryTitle.frame = CGRectMake(0, startingY, self.view.bounds.width, 50)
let secondY = startingY + 50
self.categoryIntro.frame = CGRectMake(0, secondY, self.view.bounds.width, secondY + self.categoryIntro.contentSize.height)
let thirdY = secondY + self.categoryIntro.contentSize.height
self.imageView.frame = CGRectMake(0, thirdY, self.view.bounds.width, thirdY + image.size.height)
let fourthY = thirdY + image.size.height
self.categoryParagraph.frame = CGRectMake(0, fourthY, self.view.bounds.width, fourthY + self.categoryParagraph.contentSize.height)
let fifthY = fourthY + self.categoryParagraph.contentSize.height
self.categoryConclusion.frame = CGRectMake(0, fifthY, self.view.bounds.width, fifthY + self.categoryConclusion.contentSize.height)

Thanks so much!


If you want to increment the variable you're storing y in, you should use a var. The let keyword is for variables you want to keep constant.

You also don't need to add the y position to the last parameter of CGRectMake. The height will be added to the y position set in the second parameter.

You can then use the final value of the y position variable to update your scrollview's contentsize.

Additionally, if you've already positioned your scrollview below the status bar, you would start at zero.

You can then add the height of each view you add:

var yPos = 0; 
self.categoryTitle.frame = CGRectMake(0, yPos, self.view.bounds.width, 50)
yPos += self.categoryTitle.frame.size.height;
self.categoryIntro.frame = CGRectMake(0, yPos, self.view.bounds.width,  self.categoryIntro.contentSize.height)
yPos += self.categoryIntro.frame.size.height;
self.imageView.frame = CGRectMake(0, yPos, self.view.bounds.width, image.size.height);
yPos += self.imageView.frame.size.height;