How to make a UIScrollView Programmatically

Ok, so I’ve stilll never made this work in interface builder. But it’s not that hard to make it in code.

You want to add a scroll view to the middle of your screen, in your view controller.m file:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    NSLog(@"viewDidLoad");
    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, 107.0, 320.0, 415.0)];
    contentImage = [UIImage imageNamed:@"video_wall.png"];
    contentImageView = [[UIImageView alloc] initWithImage:contentImage];
    contentView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 463.0)];

    [contentView addSubview:contentImageView];
    [scrollView addSubview:contentView];
    [scrollView setContentSize:CGSizeMake(320.0, 463.0)];

    [[self view] addSubview:scrollView];
}

Make sure you manage these variables however you do, for instance I have in my .h file:

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIImageView *contentImageView;
@property (nonatomic, strong) UIImage *contentImage;

So there you have it.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.