Create UIScrollView Programmatically

Discussion in 'iPhone/iPad Programming' started by printf, Jun 11, 2010.

  1. macrumors regular

    Joined:
    Aug 27, 2008
    #1
    i'm going off this programming guide on how to create a scrollview programmatically, but i can't get it to work as there's a few things i don't understand http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/NSScrollViewGuide/Articles/Creating.html

    right now, i have a window, a custom uiview and a viewcontroller. i try to alloc the uiscrollview inside the viewcontroller's loadView method but it crashes with an unrecognized selector exception.

    the problem here is i don't really understand the relationship between the scrollview and the view controller. i know i'll add my custom uiview as a subview to the scrollview, but beyond that not much.
     
  2. Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #2
    Let's see your code.
     
  3. thread starter macrumors regular

    Joined:
    Aug 27, 2008
    #3
    ok.

    //app delegate's didFinishLaunchingWithOptions:
    Code:
    viewController = [[ViewController alloc] initWithFrame:CGRectMake(0.0, 0.0, 320, 480)];
    	
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];	
    
    //relevant methods from view controller
    Code:
    -(id)initWithFrame:(CGRect)rect {
    	NSLog(@"initWithFrame");
    	if (self = [super init]) {		
    		scrollView = [[UIScrollView alloc] initWithFrame:rect];
    	}
    	return self;
    }
    
    - (void)loadView {
    	NSLog(@"loadView");
    	
    	myView = [[CustomView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320, 480)];
    	myView.autoresizesSubviews = YES;
    	self.view = myView;        
    
    	[scrollView setContentSize: CGSizeMake(320, 960)];	// twice as long as the screen
    	[scrollView setFrame:CGRectMake(0, 0, 320, 480)];
    	
    }
    
    - (void)viewWillAppear:(BOOL)animated {
    	[super viewWillAppear:animated];	
    	
    	scrollView.contentSize = CGSizeMake(self.view.frame.size.width,myView.frame.size.height);
    	[scrollView addSubview:myView];	
    }
    
     
  4. thread starter macrumors regular

    Joined:
    Aug 27, 2008
    #4
    ok, i got it working - finally.

    basically it was a small oversight on my part. by changing this:

    Code:
    self.view = myView
    
    to this:

    Code:
    self.view = scrollView;
    
    it now works.
     

Share This Page