0

我有一个RootViewController创建一个SecondViewController. 在SecondViewControllerin 中viewDidAppear,我创建了 aUIScrollView和 aUIPageControl并将它们添加到视图中。我也这样做:scrollview.delegate = self。是SecondViewController一个<UIScrollViewDelegate>。我scrollViewDidScroll也在SecondViewController. 所有这些工作、编译和运行。但是,当我触摸 时UIScrollView,应用程序崩溃了。对于我的生活,我无法弄清楚为什么。这是最愚蠢的问题,但我无法解决。

它与这个问题非常相似:UIScrollView EXC_BAD_ACCESS crash in iOS 但是,我尝试了这些解决方案,但都没有奏效。

我在下面粘贴了一些代码。我真的很感激帮助。

根视图控制器:

- (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];
}

第二视图控制器:

- (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;
}
4

1 回答 1

1

您的secondViewController对象被释放,因为它没有保留在任何地方,只有它的视图被保留,因为它被添加为子视图。您还需要保留 secondViewController 的对象。

于 2013-09-27T04:25:04.153 回答