Swift : UIPageControl 自动滑动 iOS 9

Swift : UIPageControl auto swipe in iOS 9

我在 UICollectionViewCell 中放置了 ImageView,在其下方放置了一个 PageControl。两者都通过编程方式连接。

但是,我希望 auto swipe (say every 5 seconds) the images should auto swipe. 如果用户手动滑动,那么它也应该发生。此外,当页面控件到达最后时,它应该从第一个开始。

下面是我用过的代码:

 var offersImages: [UIImage] = [     //Array of Banners
        UIImage(named: "default-banner.png")!,
        UIImage(named: "default-banner.png")!,
        UIImage(named: "default-banner.png")!,
        UIImage(named: "default-banner.png")!,
    ]

 override func viewDidLoad() {
        super.viewDidLoad()

        self.objPageControl.currentPage = 0
        self.objPageControl.numberOfPages = self.offersImages.count
    }

 func scrollViewDidScroll(scrollView: UIScrollView) {
        let pageWidth : CGFloat = self.objBannerCollectionView.frame.size.width
        self.objPageControl.currentPage = Int(self.objBannerCollectionView.contentOffset.x/pageWidth)
    }  

如何在 Swift 中完成?

参考以下link,将有助于解决您的问题。

Horizontal Paging

下面的代码解决了我的问题:

   //MARK:- viewDidLoad
    override func viewDidLoad() {
        super.viewDidLoad()

        . . .

         _ = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: #selector(moveToNextPage), userInfo: nil, repeats: true)
    }

     func moveToNextPage (){
        let pageWidth:CGFloat = self.objBannerCollectionView.frame.width
        let maxWidth:CGFloat = pageWidth * 4
        let contentOffset:CGFloat = self.objBannerCollectionView.contentOffset.x

        var slideToX = contentOffset + pageWidth

        if  contentOffset + pageWidth == maxWidth {
                slideToX = 0
        }

        self.objBannerCollectionView.scrollRectToVisible(CGRect(x:slideToX, y:0, width:pageWidth, height:self.objBannerCollectionView.frame.height), animated: true)
    }