How to create a UIScrollView Programmatically?

Ethan Mick picture Ethan Mick · Jun 8, 2010 · Viewed 81.9k times · Source

Alright, so the key here is I'm not using IB at all, because the View I'm working with is created programmatically. The UIView covers the lower half the screen, and has a bunch of buttons on it. However, I want to add more buttons to the UIView, without making it any larger. To do so, I want to make a UIScrollView inside the view, which will allow me to add more buttons off screen so the user can scroll to them. I think that's how it works.

self.manaView = [[[UIView alloc] initWithFrame:frame] autorelease];
self.manaView.backgroundColor = [UIColor purpleColor];

UIScrollView *scroll = [UIScrollView alloc];
scroll.contentSize = CGSizeMake(320, 400);
scroll.showsHorizontalScrollIndicator = YES;
[self.manaView addSubview:scroll];

The first part of the code iniates my UIView, which works great, but I can't figure out how to make the UIScrollView programmatically and add it to the view, and then add the buttons to it.

UIButton *ret2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
ret2.tag = 102;
ret2.frame = CGRectMake(255, 5, 60, 50);
[ret2 setTitle:@"Return" forState:UIControlStateNormal];
[ret2 addTarget:self action:@selector(flipAction:) forControlEvents:UIControlEventTouchUpInside];
[scroll addSubview:ret2];

When I did that, the button simply disappeared off my screen. So How do I do this correctly? Thank you for your help!

Answer

Ole Begemann picture Ole Begemann · Jun 8, 2010

Instead of:

UIScrollView *scroll = [UIScrollView alloc];

do this (setting the frame to however big you want the scroll view to be):

UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:...];