许多视图控制器 - 性能问题

时间:2015-11-05 18:09:31

标签: ios swift uiviewcontroller

我有一个IOS应用程序,可让用户刷过数周的笔记。每周都是一个UIViewController - 视图控制器之间的滑动和切换由UIPageViewController处理。

启动时,所有视图控制器都会使用其数据进行初始化。

当用户滑动时,我会抓住这样的视图控制器:

func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
    if let currentPageViewController = viewController as? SinglePageViewController {
      let currentIndex = currentPageViewController.index
      return self.weeks[currentIndex - 1]
    }
    return nil
  }

应用程序完美无瑕,直到使用了很多周,因此许多视图控制器。启动时间开始成为一个问题 - 这种情况只会随着时间的推移而变得更糟。

当用户滑动时,我已经开始使用初始化每个视图控制器。像这样:

    func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
        if let currentPageViewController = viewController as? SinglePageViewController {
          let currentIndex = currentPageViewController.index
          let newVC = SinglePageViewController()
          newVC.index = currentIndex - 1
          return newVC
        }
        return nil
      }

这种方法很有效,启动时间很长 - 但是,滑动现在变得迟钝而且根本不光滑。

有人可以就如何解决这个问题提出建议吗?

2 个答案:

答案 0 :(得分:1)

第二种方法(按需创建)是正确的方法。如果swipping变慢,那么因为你在init(),viewDidLoad,viewWillAppear等花费了很多CPU时间......查看初始化并将每个CPU密集型任务移动到后台线程。

如果您依赖数据来创建ViewController,那么您必须提前预加载数据。但是不需要预加载超过2或3个数据的数据。如果需要花费很多时间并且您仍遇到性能问题,那么您必须接受设备不够快,无法满足您的要求,并且必须向用户提供加载指示器。 (比如UIActivityIndi​​cator)

如果您在优化初始化方面需要帮助,请发布您的代码。

答案 1 :(得分:0)

在UIScrollView中使用过多的UIScrollViews时遇到了类似的问题。我的解决方案是使用scrollViewDidScroll委托方法监视用户所在的位置,连接到我的容器滚动视图,并根据用户滚动的方向填充/删除视图。

let direction = scrollView.panGestureRecognizer.translationInView(scrollView.superview!)方法中scrollViewDidScroll可以获得的方向。

这种方法适合你吗?如果你愿意,我可以给你更多我的代码!

相关问题