Saturday, June 09, 2012

More CGSize/CGRect Stuff. Adding UIView to UIScrollView dynamically in a horizontal layout.

Ok so let's say I'm dynamically adding two UIViews to a UIScrollView in a horizontal layout. I want the second UIView to be places underneath the first UIView (with a padding of 2 pixels). Here's how I did it:

1. myUIScrollView is the name of my UIScrollView
2. myView1 is the name of my first UIView.
3. myView2 is the name of my second UIView.

CGRect tempFrame = [myView1 frame]; //get frame/CGRect for myView1
[myUIScrollView addSubview:myView1]; //add myView1 to the UIScrollView

//get the size of myView1, and make the next Y co-ord its height+2.
int nextY = tempFrame.origin.y + myView1.bounds.size.height+2;

tempFrame = [myView2 frame]; //get the frame/CGRect for myView2
myView2.origin.y = nextY; //set the Y co-ord to that of myView1's height+2.
myView2.frame = tempFrame; //apply the frame to myView1.
[myUIScrollView addSubview:myView2]; //add myView2 to the UIScrollView object.


I'm sure there's a better way to do this. Somehow?

No comments:

Post a Comment