Search code examples
iosobjective-cipaduiscrollviewuiscrollviewdelegate

App crashes when UIScrollView touched


I have a RootViewController which creates a SecondViewController. Inside the SecondViewController in viewDidAppear, I create a UIScrollView and a UIPageControl and add them to the view. I also do this: scrollview.delegate = self. The SecondViewController is a <UIScrollViewDelegate>. I have also implemented scrollViewDidScroll inside the SecondViewController. All of this works, compiles and runs. However, when I touch the UIScrollView, the app crashes. For the life of me, I cannot figure out why. It is the stupidest problem, but I cannot solve it.

It is very similar to this problem: UIScrollView EXC_BAD_ACCESS crash in iOS However, I tried those solutions and none of them work.

I have pasted some code below. I really appreciate the help.

RootViewController:

- (void)viewDidAppear:(BOOL)animated
{
    SecondViewController *secondViewController = [[SecondViewController alloc] init];
    secondViewController.view.frame = CGRectMake(50, 50, 925, 600);
    secondViewController.view.backgroundColor = [UIColor lightGrayColor];

    [self.view addSubview:secondViewController.view];
}

SecondViewController:

- (void)viewDidAppear:(BOOL)animated
{
    CGRect scrollViewFrame = CGRectMake(50, 50, 824, 500);
    self.scrollView = [[UIScrollView alloc] initWithFrame:scrollViewFrame];
    self.scrollView.delegate = self;
    self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width*3,
                                             self.scrollView.frame.size.height);
    self.scrollView.backgroundColor = [UIColor darkGrayColor];
    self.scrollView.showsHorizontalScrollIndicator = YES;
    self.scrollView.showsVerticalScrollIndicator = YES;
    self.scrollView.pagingEnabled = YES;

    [self.view addSubview:self.scrollView];

    CGRect pageControlFrame = CGRectMake(0, 0, 50, 20);
    self.pageControl = [[UIPageControl alloc] initWithFrame:pageControlFrame];
    self.pageControl.numberOfPages = 3;
    self.pageControl.currentPage = 0;
    self.pageControl.backgroundColor = [UIColor grayColor];

    [self.view addSubview:self.pageControl];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat pageWidth = self.scrollView.frame.size.width;
    float fractionalPage = self.scrollView.contentOffset.x / pageWidth;
    NSInteger page = lround(fractionalPage);
    self.pageControl.currentPage = page;
}

Solution

  • your secondViewController object is deallocated as it is not retained anywhere only its view is retained as it is added as subview. You also need to retain secondViewController's object.