在UIScrollView上更改页面

joh*_*ohn 56 iphone uiscrollview

我有一个10页的UIScrollView.我能够在他们之间轻弹.我还想要2个按钮(后退按钮和下一个按钮),当触摸时将转到上一页或下一页.我似乎无法找到一种方法来做到这一点.我的很多代码来自Apple的页面控制示例代码.有人可以帮忙吗?

谢谢

mjd*_*dth 136

您只需告诉按钮滚动到页面的位置:

CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * pageNumberYouWantToGoTo;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];
Run Code Online (Sandbox Code Playgroud)

  • 应该注意的是,`pageNumberYouWantToGoTo`以第0页开始而不是第1页.而你的最后一页将比实际情况少一个.(例如,要转到第7页,您将在代码中输入6) (3认同)

小智 18

scroll.contentOffset = CGPointMake(scroll.frame.size.width*pageNo, 0);
Run Code Online (Sandbox Code Playgroud)


Pon*_*tus 18

这是Swift 4的一个实现:

func scrollToPage(page: Int, animated: Bool) {
    var frame: CGRect = self.scrollView.frame
    frame.origin.x = frame.size.width * CGFloat(page)
    frame.origin.y = 0
    self.scrollView.scrollRectToVisible(frame, animated: animated)
}
Run Code Online (Sandbox Code Playgroud)

并且可以通过调用轻松调用:

self.scrollToPage(1, animated: true)
Run Code Online (Sandbox Code Playgroud)

编辑:

一个更好的方法是支持水平和垂直分页.这是一个方便的扩展:

extension UIScrollView {

    func scrollTo(horizontalPage: Int? = 0, verticalPage: Int? = 0, animated: Bool? = true) {
        var frame: CGRect = self.frame
        frame.origin.x = frame.size.width * CGFloat(horizontalPage ?? 0)
        frame.origin.y = frame.size.width * CGFloat(verticalPage ?? 0)
        self.scrollRectToVisible(frame, animated: animated ?? true)
    }

}
Run Code Online (Sandbox Code Playgroud)

这将在UIScrollView上创建一个扩展,您可以在其中滚动到任何页面,垂直或水平.

self.scrollView.scrollTo(horizontalPage: 0)
self.scrollView.scrollTo(verticalPage: 2, animated: true)
self.scrollView.scrollTo(horizontalPage: 1, verticalPage: 2, animated: true)
Run Code Online (Sandbox Code Playgroud)


Chu*_*y47 14

scrollRectToVisible对我不起作用,所以我不得不为contentOffset设置动画.此代码适用于swift 3.

func scrollToPage(_ page: Int) {
    UIView.animate(withDuration: 0.3) { 
        self.scrollView.contentOffset.x = self.scrollView.frame.width * CGFloat(page)
    }
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*dez 8

对于Swift 3,这是一个非常方便的扩展:

extension UIScrollView {
    func scrollToPage(index: UInt8, animated: Bool, after delay: TimeInterval) {
        let offset: CGPoint = CGPoint(x: CGFloat(index) * frame.size.width, y: 0)
        DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: {
            self.setContentOffset(offset, animated: animated)
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

你这样称呼它:

scrollView.scrollToPage(index: 1, animated: true, after: 0.5)
Run Code Online (Sandbox Code Playgroud)