2010-02-10 23 views
121

Tengo un UIScrollView que tiene varias vistas. Cuando un usuario mueve su dedo, la vista se desplaza hacia la derecha o hacia la izquierda dependiendo de la dirección del deslizamiento del dedo. Básicamente mi código funciona de una manera similar a la aplicación de fotos de iPhone. Ahora, ¿hay alguna manera de que pueda hacer lo mismo programáticamente para que termine con una presentación de diapositivas que se ejecute por sí sola con un clic de un botón y una pausa configurable entre cada desplazamiento?Desplazamiento programático de UIScrollView

¿Cómo se puede realmente hacer presentaciones de diapositivas con UIScrollView?

Respuesta

317

Puede desplazarse hasta cierto punto en una vista de desplazamiento con una de las siguientes declaraciones en Objective-C

[scrollView scrollRectToVisible:CGRectMake(x, y, 1, 1) animated:YES]; 
// or 
[scrollView setContentOffset:CGPointMake(x, y) animated:YES]; 

o Swift

scrollView.scrollRectToVisible(CGRect(x: x, y: y, width: 1, height: 1), animated: true) 
// or 
scrollView.setContentOffset(CGPoint(x: x, y: y), animated: true) 

Ver el guide "Scrolling the Scroll View Content" from Apple as well.

Para hacer presentaciones de diapositivas con UIScrollView, organice todas las imágenes en la vista de desplazamiento, configure un temporizador repetido, luego -setContentOffset:animated: cuando se dispare el temporizador.

Pero un enfoque más eficiente es usar 2 vistas de imágenes y cambiarlas usando transiciones o simplemente cambiando de lugar cuando el temporizador se dispara. Vea iPhone Image slideshow para más detalles.

+1

fresca. Sí, encontré que setContentOffset funciona, pero realmente quería que esto sucediera de forma animada. 'animado: SÍ' hizo el truco. – climbon

+2

Simplemente complementando la respuesta, para pasar horizontalmente a la siguiente "página" en UIScrollView (suponiendo que está codificando para iPhone), para el parámetro x use '(myScrollView.contentOffset.x +320)'. – Giovanni

+2

@niraj gracias amigo ... en '(myScrollView.contentOffset.x +320)' yace la clave! –

10

Otra forma es

scrollView.contentOffset = CGPointMake(x,y); 
+13

Esto es exactamente lo mismo que la respuesta aceptada. Y 'CGPoint' debería ser' CGPointMake'. –

+0

Me gustan las respuestas simples como esta. – quemeful

+0

En realidad, esto no es lo mismo que la respuesta aceptada. La respuesta aceptada tiene una opción de animación, que algunas aplicaciones podrían haber configurado en SÍ. – Rickster

35

Si desea un control sobre la duración y el estilo de la animación, que puede hacer:

[UIView animateWithDuration:2.0f delay:0 options:UIViewAnimationOptionCurveLinear animations:^{ 
    scrollView.contentOffset = CGPointMake(x, y); 
} completion:NULL]; 

ajustar la duración (2.0f) y las opciones (UIViewAnimationOptionCurveLinear) a ¡gusto!

1
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    board=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.height, 80)]; 
    board.backgroundColor=[UIColor greenColor]; 
    [self.view addSubview:board]; 
    // Do any additional setup after loading the view. 
} 


-(void)viewDidLayoutSubviews 
{ 


    NSString *[email protected]"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 

    index=1; 
    for (int i=0; i<20; i++) 
    { 
     UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake(-50, 15, 50, 50)]; 
     lbl.tag=i+1; 
     lbl.text=[NSString stringWithFormat:@"%c",[str characterAtIndex:arc4random()%str.length]]; 
     lbl.textColor=[UIColor darkGrayColor]; 
     lbl.textAlignment=NSTextAlignmentCenter; 
     lbl.font=[UIFont systemFontOfSize:40]; 
     lbl.layer.borderWidth=1; 
     lbl.layer.borderColor=[UIColor blackColor].CGColor; 
     [board addSubview:lbl]; 
    } 

    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(CallAnimation) userInfo:nil repeats:YES]; 

    NSLog(@"%d",[board subviews].count); 
} 


-(void)CallAnimation 
{ 

    if (index>20) { 
     index=1; 
    } 
    UIView *aView=[board viewWithTag:index]; 
    [self doAnimation:aView]; 
    index++; 
    NSLog(@"%d",index); 
} 

-(void)doAnimation:(UIView*)aView 
{ 
    [UIView animateWithDuration:10 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{ 
     aView.frame=CGRectMake(self.view.frame.size.height, 15, 50, 50); 
    } 
        completion:^(BOOL isDone) 
    { 
     if (isDone) { 
      //do Somthing 
         aView.frame=CGRectMake(-50, 15, 50, 50); 
     } 
    }]; 
} 
+7

Considere agregar texto a su respuesta, no solo código puro – user1781290

6

por animación en Swift

scrollView.setContentOffset(CGPointMake(x, y), animated: true) 
1
scrollView.setContentOffset(CGPoint(x: y, y: x), animated: true) 
1
[Scrollview setContentOffset:CGPointMake(x, y) animated:YES]; 
3

Swift 3

let point = CGPoint(x: 0, y: 200) // 200 or any value you like. 
    scrollView.contentOffset = point 
Cuestiones relacionadas