在UIScrollView上更改页面
我有一个10页的UIScrollView。 我可以在他们之间轻弹。 我也想有2个button(一个后退button和一个下一个button),当被触摸的时候会进入上一页或下一页。 我似乎无法想出一个方法来做到这一点,虽然。 我的很多代码来自Apple的页面控制示例代码。 任何人都可以帮忙吗?
谢谢
你只要告诉button滚动到页面的位置:
CGRect frame = scrollView.frame; frame.origin.x = frame.size.width * pageNumberYouWantToGoTo; frame.origin.y = 0; [scrollView scrollRectToVisible:frame animated:YES];
scroll.contentOffset = CGPointMake(scroll.frame.size.width*pageNo, 0);
scrollRectToVisible没有为我工作,所以我不得不animation的contentOffset。 这个代码工作在swift 3。
func scrollToPage(_ page: Int) { UIView.animate(withDuration: 0.3) { self.scrollView.contentOffset.x = self.scrollView.frame.width * CGFloat(page) } }
这里是Swift的实现:
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) }
并很容易使用:
self.scrollToPage(1, animated: true)
对于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) }) } }
你这样称呼它:
scrollView.scrollToPage(index: 1, animated: true, after: 0.5)
你可以这样做:
CGRect lastVisibleRect; CGSize contentSize = [_scrollView contentSize]; lastVisibleRect.size.height = contentSize.height; lastVisibleRect.origin.y = 0.0; lastVisibleRect.size.width = PAGE_WIDTH; lastVisibleRect.origin.x = contentSize.width - PAGE_WIDTH * (_totalItems - pageIndex); // total item of scrollview and your current page index [_scrollView scrollRectToVisible:lastVisibleRect animated:NO];
这是一个快速的静态方法:
static func scrollToPage(scrollView: UIScrollView, page: Int, animated: Bool) { var frame: CGRect = scrollView.frame frame.origin.x = frame.size.width * CGFloat(page); frame.origin.y = 0; scrollView.scrollRectToVisible(frame, animated: animated) }
如果scrollRectToVisible不起作用,请尝试以下操作:
let frame = scrollView.frame let offset:CGPoint = CGPoint(x: CGFloat(sender.currentPage) * frame.size.width, y: 0) self.scrollView.setContentOffset(offset, animated: true)
首先创build一个UIScrollView扩展,如下所示:
extension UIScrollView { func setCurrentPage(position: Int) { var frame = self.frame; frame.origin.x = frame.size.width * CGFloat(position) frame.origin.y = 0 scrollRectToVisible(frame, animated: true) } }
然后只是打电话:
self.scrollView.setCurrentPage(position: 2) // where 2 is your desired page
除了mjdth添加的代码之外 ,请记住将其放在viewWillAppear或viewDidAppear中 。
CGRect frame = scrollView.frame; frame.origin.x = frame.size.width * pageNumberYouWantToGoTo; frame.origin.y = 0; [scrollView scrollRectToVisible:frame animated:YES];