How to create a UIScrollView Programmatically?

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!


Solution 1:

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:...];

Solution 2:

This may be helpful to you for creating the uiscrollview programmatically
http://unconditionalloop.blogspot.com/2011/04/uiscrollview-programmatically.html

  UIScrollView *scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];   
     NSInteger viewcount= 4;  
     for(int i = 0; i< viewcount; i++) { 

        CGFloat y = i * self.view.frame.size.height;  
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, y,self.view.frame.size.width, self .view.frame.size.height)];       
        view.backgroundColor = [UIColor greenColor];  
        [scrollview addSubview:view];  
        [view release];  
     }    
  scrollview.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height *viewcount);   
  [self.view addSubview:scrollview];

Solution 3:

try this,

{

        scrollview=[[UIScrollView alloc]initWithFrame:CGRectMake(0,0,320,480)]; 
        scrollview.showsVerticalScrollIndicator=YES;
        scrollview.scrollEnabled=YES;
        scrollview.userInteractionEnabled=YES;
        [self.view addSubview:scrollview];
        scrollview.contentSize = CGSizeMake(width,height);

    [scrollview release];
}