Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set size of UIScrollView frame programmatically?

I am newbie so my question can be really obvious, but I didn't find any solution so far.

I did in IB UIScrollView and connected it with File's Owner. I would like to set now the frame size of my UIScrollView (named ScrollView).

const CGFloat BoardWidth = 320;
const CGFloat BoardHeight = 400;

//I tried this way but 'Expression is assignable' - said Xcode
ScrollView.frame.size.width = BoardWidth;
ScrollView.frame.size.height = BoardWidth;

So how can I the easiest set own sizes of ScrollView frame?

like image 371
Konrad Kolasa Avatar asked Feb 18 '12 11:02

Konrad Kolasa


2 Answers

CGRect scrollFrame = CGRrectMake(x, y, w, h);
ScrollView.frame = scrollFrame;

Or if you need only to change the width and height;

CGRect scrollFrame;
scrollFrame.origin = ScrollView.frame.origin;
scrollFrame.size = CGSizeMake(w, h);
ScrollView.frame = scrollFrame;

Edit keeping the center unchanged:

CGRect scrollFrame;
CGFloat newX = scrollView.frame.origin.x + (scrollView.frame.size.width - w) / 2;
CGFloat newY = scrollView.frame.origin.y + (scrollView.frame.size.height - y) / 2;
scrollFrame.origin = CGPointMake(newX, newY);
scrollFrame.size = CGSizeMake(w, h);
scrollView.frame = scrollFrame;
like image 189
sch Avatar answered Oct 24 '22 09:10

sch


you need to do this, for example.

ScrollView.frame = CGRectMake(0, 0, BoardWidth, BoardHeight);

Once done you need also to set contentSize property. It's the area that 'extends' behind the frame of your UIScrollView.

If you want to scroll only horizontally:

ScrollView.contentSize = CGSizeMake(w * BoardWidth, BoardHeight);

If you want to scroll only vertically:

ScrollView.contentSize = CGSizeMake(BoardWidth, h * BoardHeight);

If you want to scroll both horizontally and vertically:

ScrollView.contentSize = CGSizeMake(w * BoardWidth, h * BoardHeight);

where w and h are generic values to increment your width and/or your height.

If you want have an horizontal (for example) discrete scroll (e.g. you have some pages with the same dimension of your screen).

ScrollView.pagingEnabled = YES;
ScrollView.contentSize = CGSizeMake(p * BoardWidth, BoardHeight);

where p is the number of pages you want to display.

Hope it helps.

like image 5
Lorenzo B Avatar answered Oct 24 '22 09:10

Lorenzo B