Search code examples
iosobjective-cuiscrollviewdelegatesscroll-paging

UIScrollView delegate properties not working properly


My issue is that the properties (is that the right word?) of my scrollView are not working. I am trying to get the scrollView to page, but it seems as though it ignores my line of code that says

[scrollView setPagingEnabled:YES];

The scrollView scrolls up and down as well as side to side (the contentSize is set), but it does not snap to a page, and testing other delegate properties that aren't working it appears that the problem is a result of this.

It seems as though I have done something wrong in declaring the delegate, which is supposed to be self. Here is the header of my .h that makes DayViewController a UIScrollView delegate

@interface DayViewController : UIViewController <UIScrollViewDelegate> {
UIScrollView *scrollView;
//other code......
}

Here is the relevant part of my .m file where the delegate is set to self, and I try to adjust properties of the UIScrollView.

- (void)viewDidLoad
{
[super viewDidLoad];
tester = [Global tester];
cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
viewsInMemory = [[NSMutableArray alloc] init];

for (int i = 0; i < 3; i++) {
    [viewsInMemory insertObject:[NSNull null] atIndex:i];
}

scrollView = [[UIScrollView alloc] init];
scrollView.delegate = self;
[scrollView setScrollEnabled:YES];
[scrollView setPagingEnabled:YES];
scrollView = [[UIScrollView alloc] initWithFrame:(CGRectMake(0, 0, 320, self.view.frame.size.height))];
scrollView.backgroundColor = [UIColor lightGrayColor];

[self loadInitialDays];


[scrollView addSubview:(currentDayView)];
[self.view addSubview:(scrollView)];

}

I understand that other parts of my code might look inefficient or whatever, but that is not what I am asking for help with. The only thing that I need is for one of you wonderful people to figure out why the delegate is not working. Thanks a bunch!


Solution

  • The issue is with this line:

    scrollView = [[UIScrollView alloc] initWithFrame:(CGRectMake(0, 0, 320, self.view.frame.size.height))];.

    You're re-initializing scrollView so all of the above properties are ignored and the only property actually set is the backgroundColor property.

    To fix this change this line:

    scrollView = [[UIScrollView alloc] init];

    to

    scrollView = [[UIScrollView alloc] initWithFrame:(CGRectMake(0, 0, 320, self.view.frame.size.height))];.

    So your final code looks like this:

    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height)];
    scrollView.delegate = self;
    [scrollView setScrollEnabled:YES];
    [scrollView setPagingEnabled:YES];
    scrollView.backgroundColor = [UIColor lightGrayColor];