Scrollview和uiview在SWIFT淡出淡出

时间:2016-06-10 16:55:03

标签: swift uiscrollview uiimageview fadein fadeout

我想实现淡入/淡出过渡。 我的结构是:

UIView
|-UIScrollView // contains array of UILabels
|-UIImageView1
|-UIImageView2
|-UIImageView3
|-UIImageView4

如果我在所有屏幕的宽度上按水平滚动,一切正常。 但是,如果我向右或向左滚动一点,我会在另一个方向上滚动回滚,使我的不透明度变得错误(我可以看到一些下一张和上一张图像)。

这是我的代码:

private var lastContentOffset: CGFloat = 0

func scrollViewDidScroll(scrollView: UIScrollView) {

    let pageWidth:CGFloat = self.scrollViewLabels.frame.size.width
    let page:Int = Int(floor((self.scrollViewLabels.contentOffset.x - pageWidth / 2) / pageWidth) + 1)

    if (self.lastContentOffset > scrollView.contentOffset.x) {
        // move right

        let opacityPercent:CGFloat = (CGFloat(scrollView.contentOffset.x) / pageWidth ) / CGFloat(self.pageControl.currentPage + 1)

        if self.pageControl.currentPage  > 0  {
            self.images[self.pageControl.currentPage].alpha =  opacityPercent

            if self.pageControl.currentPage - 1 >= 0 {
                self.images[self.pageControl.currentPage - 1].alpha = 1 - opacityPercent
            }   
        }
    }
    else if (self.lastContentOffset < scrollView.contentOffset.x) {
        // move left

        let opacityPercent:CGFloat = (CGFloat(scrollView.contentOffset.x) / pageWidth ) / CGFloat(self.pageControl.currentPage + 1)

        if self.pageControl.currentPage  < self.images.count - 1 {
            self.images[self.pageControl.currentPage].alpha = 1 - opacityPercent

            if self.pageControl.currentPage + 1 <= self.images.count - 1 {
                self.images[self.pageControl.currentPage + 1].alpha = opacityPercent

            }
        }

    }

    // update the new position acquired
    self.lastContentOffset = scrollView.contentOffset.x

}


func scrollViewDidEndDecelerating(scrollView: UIScrollView) {

    let pageWidth:CGFloat = self.scrollViewLabels.frame.size.width
    let page:Int = Int(floor((self.scrollViewLabels.contentOffset.x - pageWidth / 2) / pageWidth) + 1)

    if (self.pageControl.currentPage != page) {

        self.pageControl.currentPage = page
        self.page = page
        self.scrollView.contentOffset = CGPointMake(self.view.frame.size.width * CGFloat(page), 0)


    } 


}

0 个答案:

没有答案