Change page on UIScrollView

后端 未结 12 1327
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 18:45

I have a UIScrollView with 10 pages. I am able to flick between them. I also want to have 2 buttons (a back button and a next button) which when touched will go to the previ

12条回答
  •  天命终不由人
    2020-12-04 19:24

    Here is an implementation for 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)
    }
    

    and is easily invoked by calling:

    self.scrollToPage(1, animated: true)
    

    Edit:

    A nicer way of doing this is to support both horizontal and vertical pagination. Here is a convenient extension for that:

    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)
        }
    
    }
    

    This creates an extension on UIScrollView where you can scroll to any page, vertical or horisontal.

    self.scrollView.scrollTo(horizontalPage: 0)
    self.scrollView.scrollTo(verticalPage: 2, animated: true)
    self.scrollView.scrollTo(horizontalPage: 1, verticalPage: 2, animated: true)
    

提交回复
热议问题