首页 文章

Swift:从ScrollView更新UIPageControl

提问于
浏览
1

我似乎遇到了一些使UIPageControl工作的问题 .

我有一个包含ScrollView的ViewController . 此ScrollView加载可以刷过的nib文件 . 看图:

enter image description here

以下是加载这些代码的代码:

self.addChildViewController(vc0)
self.displayReportView.addSubview(vc0.view)
vc0.didMoveToParentViewController(self)

var frame1 = vc1.view.frame
frame1.origin.x = self.view.frame.size.width
vc1.view.frame = frame1
self.addChildViewController(vc1)
self.displayReportView.addSubview(vc1.view)
vc1.didMoveToParentViewController(self)

// And so on
...

这工作正常,因为他们正确滚动等 .

现在,在ViewController(一个持有scrollview)上我添加了委托:

UIScrollViewDelegate

创建了一些变量:

var frame: CGRect = CGRectMake(0, 0, 0, 0)
 var colors:[UIColor] = [UIColor.redColor(), UIColor.blueColor(), UIColor.greenColor(), UIColor.yellowColor()]
 var pageControl : UIPageControl = UIPageControl(frame: CGRectMake(50, 300, 200, 20))

我添加了一些所需的功能:

func configurePageControl() {
    // The total number of pages that are available is based on how many available colors we have.

    self.pageControl.numberOfPages = 4
    self.pageControl.currentPage = 0
    self.pageControl.tintColor = UIColor.redColor()
    self.pageControl.pageIndicatorTintColor = UIColor.blackColor()
    self.pageControl.currentPageIndicatorTintColor = UIColor.greenColor()
    self.view.addSubview(pageControl)

}


// MARK : TO CHANGE WHILE CLICKING ON PAGE CONTROL
func changePage(sender: AnyObject) -> () {
    let x = CGFloat(pageControl.currentPage) * displayReportView.frame.size.width
    displayReportView.setContentOffset(CGPointMake(x, 0), animated: true)
}


func scrollViewDidEndDecelerating(scrollView: UIScrollView) {

    let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
    pageControl.currentPage = Int(pageNumber)
}

现在,当我运行应用程序时,滚动视图点显示,但是当我滑动时,它们不会更新 .

问题

如何更新点以反映显示的视图?

如果您需要我的代码中的任何其他内容来查看功能,请告诉我们 .

2 回答

  • 6

    如果你有一个分页滚动视图,你当然可以做你正在描述的内容;我有一个使用此代码的示例:

    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        let x = scrollView.contentOffset.x
        let w = scrollView.bounds.size.width
        pageControl.currentPage = Int(x/w)
    }
    

    除了你的 round 之外,你的代码看起来很多,这让我认为你的代码应该可行 . 这让我觉得别的东西只是错误的配置 . 这是一个分页滚动视图吗?您是否记得将此对象设为滚动视图的 delegate ?使用日志记录或断点确保您的 scrollViewDidEndDecelerating 首先被调用 .

    但是,我只想指出,您正在描述的配置实际上是UIPageViewController免费提供的 - 带有视图控制器视图的滚动视图以及页面控件 - 因此您可能希望使用它 .

  • 0

    我会用 UICollectionView 替换滚动视图 . 这样你就可以免费获得分页,而且会更好,因为分页将开箱即用,而不必计算帧偏移量 .

    一定要设置 collectionView.pagingEnabled = true

    要获取当前页码,请执行 collectionView.indexPathsForVisibleItems().first?.item

    要更改页面:

    collectionView.scrollToItemAtIndexPath(newIndexPath, atScrollPosition: CenteredHorizontally, animated: true)

相关问题