Cambiar página en UIScrollView


Tengo un UIScrollView con 10 páginas. Soy capaz de moverme entre ellos. También quiero tener 2 botones (botón atrás y un botón siguiente), que cuando le tocó ir a la página anterior o siguiente. Parece que no puedo encontrar una manera de hacer esto. Gran parte de mi código proviene del código de ejemplo de control de página de Apple. ¿Alguien puede ayudar?

Gracias

Author: john, 2009-12-18

11 answers

Simplemente le dices a los botones que se desplacen a la ubicación de la página:

CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * pageNumberYouWantToGoTo;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];
 128
Author: mjdth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-18 07:23:34
scroll.contentOffset = CGPointMake(scroll.frame.size.width*pageNo, 0);
 18
Author: Mr.Guru.Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-02 15:25:43

ScrollRectToVisible no funcionaba para mí, así que tuve que animar el contentOffset. Este código funciona en swift 3.

func scrollToPage(_ page: Int) {
    UIView.animate(withDuration: 0.3) { 
        self.scrollView.contentOffset.x = self.scrollView.frame.width * CGFloat(page)
    }
}
 11
Author: Chuy47,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-26 16:07:43

Aquí está una implementación para 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)
}

Y se invoca fácilmente llamando:

self.scrollToPage(1, animated: true)

Editar:

Una forma más agradable de hacer esto es soportar la paginación horizontal y vertical. Aquí hay una extensión conveniente para eso:

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

}

Esto crea una extensión en UIScrollView donde puede desplazarse a cualquier página, vertical u horisontal.

self.scrollView.scrollTo(horizontalPage: 0)
self.scrollView.scrollTo(verticalPage: 2, animated: true)
self.scrollView.scrollTo(horizontalPage: 1, verticalPage: 2, animated: true)
 10
Author: Pontus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-11 12:25:45

Para Swift 3 esta es una extensión que me parece muy conveniente:

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

Y lo llamas así:

scrollView.scrollToPage(index: 1, animated: true, after: 0.5)
 7
Author: David Hernandez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-26 05:02:40

Puedes hacerlo de esta manera:

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];
 2
Author: HDT,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-26 16:56:20

Aquí hay un método estático en swift:

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)
}
 2
Author: maxhud,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-02 21:03:15

Primero crea una extensión UIScrollView como:

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

}

Entonces solo llama:

self.scrollView.setCurrentPage(position: 2)  // where 2 is your desired page
 2
Author: Zahidur Rahman Faisal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-01 08:04:13

Si scrollRectToVisible no funciona, prueba esto:

let frame = scrollView.frame
    let offset:CGPoint = CGPoint(x: CGFloat(sender.currentPage) * frame.size.width, y: 0)
    self.scrollView.setContentOffset(offset, animated: true)
 0
Author: giLisH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-23 16:43:49

Solución rápida

func changePage(pageControl: UIPageControl) {

    let page = CGFloat(pageControl.currentPage)
    var frame = self.scrollView.frame
    frame.origin.x = frame.size.width * page
    frame.origin.y = 0
    self.scrollView.scrollRectToVisible(frame, animated: true)
}
 0
Author: Sazzad Hissain Khan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-03 09:55:23

Adicional a este código que mjdth añadido, recuerde que el lugar en el viewWillAppear o viewDidAppear.

CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * pageNumberYouWantToGoTo;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];
 -1
Author: Juan Reyes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-01 14:34:09