uitableviewcell tutorial ejemplo efecto customize custom apple iphone xcode ipad uitableview

iphone - tutorial - ¿UITableView desplaza suavemente con cierta velocidad?



xcode swift uitableview custom cell (8)

¿Qué hay de configurar un temporizador y luego llamar al desplazamiento cuando se dispara el temporizador?

start_index = 0; dest_index = 20; timer = [NSTimer scheduledTimerWithTimeInterval:(0.1) target:self selector:@selector(rolling) userInfo:nil repeats:YES]; - (void)rolling { start_index++; if (start_index < dest_index) { NSIndexPath *Index = [NSIndexPath indexPathForRow:start_index inSection:0]; [self.tableView scrollToRowAtIndexPath:Index atScrollPosition:UITableViewScrollPositionMiddle animated:NO]; } else { [timer invalidate]; } }

Estoy construyendo una máquina tragamonedas personalizada con una columna que existe de un uitableview.

Cuando el usuario tira de una palanca, la vista de tabla debe desplazarse a una determinada posición con un índice. Utilicé el método:

- scrollToRowAtIndexPath:atScrollPosition:animated:

Pero este método hará que la tabla se desplace con una duración constante. Así que realmente no reconocerás un giro largo o corto.

Estoy buscando una manera de: A) Ralentizar la animación de desplazamiento. O, B) Cambie la duración de la animación de desplazamiento a un valor autodefinido.

La animación de desplazamiento normal (con el dedo) muestra este efecto. Tal vez sea una idea estúpida, pero ¿es una idea invocar un método touchesBegan and touchesDidEnd en mi tableView?

Gracias ya


Busqué mucho por esta respuesta, pero al final tuve que encontrar una propia. Puede llamar al método scrollAutomatically con el número de la fila inicial como:

[self scrollAutomatically:0];

Así que esto es lo que parecía la función. Estaba tratando con una tabla que siempre tenía 3000 filas y tenía la intención de desplazarme hacia abajo.

- (void) scrollAutomatically:(int) i { __block int j = i; [UIView animateWithDuration: 0//Change this to something more for slower scrolls animations: ^{ [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:j inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO]; } completion: ^(BOOL finished){ j = j + 10;//Changing this number affects speed. if(j<=2999)//here you could provide the index of destination row [self scrollAutomatically:j]; else { //I had some code here that popped up a UIAlertView. } }]; }

Ahora llegando a la velocidad del pergamino.

PARA RODAMIENTOS REALMENTE RÁPIDOS:

Si configuro un valor con el que incremento el índice de fila (j) en cada llamada de la función a 10, es decir, si escribo j = j+10; entonces mis 3000 filas tardaron unos 9 segundos en desplazarse. (3000 * significa FPS que podría reunir). Si lo pongo a j = j+20; entonces las 3000 filas tomaron unos 4.5 segundos. Así que entiendes la idea. Para hacerlo más lento, reduzca el valor de incremento.

PARA SCROLLS LENTOS, LECTUROS:

[UIView animateWithDuration: 1.5//this will directly set your speed. n rows scrolled every 1.5 seconds.

NOTA: Si cambia los marcos de CALayers o Vistas (por ejemplo, una vista personalizada que puede haber agregado al contentView de su tableViewCell), esas animaciones comenzarán a molestarlo aquí. Durante una gran duración de la animación, serán muy visibles y es posible que vea un extraño comportamiento de la celda.

En ese caso, donde sea que cambies tus marcos, mira algo como:

[CATransaction begin]; [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; [myView.myCALayer.frame = (CGRect){ { 10, 10 }, { 100, 100 } ]; [CATransaction commit];

Encuentra la solución anterior here .

También es posible que tenga que configurar el diccionario de acciones para que la capa devuelva valores nulos para todas las acciones.

NSMutableDictionary *newActions = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NSNull null], @"sublayers", nil]; superlayer.actions = newActions;

Parece que es demasiado tarde, pero para las personas que enfrentan el mismo problema, espero que esta respuesta sea útil. Además, siéntase libre de guiarme en caso de que haya cometido algún error obvio (o no tanto).

Edición: Vaya, veo la cosa exacta por encima de mi respuesta :( De todos modos, esto es un poco más detallado y solo soy un principiante :)


Debido a que un UITableView se hereda de UIScrollView, también puede usar setContentOffset: animated: De esta manera puede hacer que su vista de tabla "desplace" una cierta cantidad de píxeles de su elección a cualquier lado que desee.

Esto se puede hacer de la misma manera con scrollToRowAtIndexPath: atScrollPosition: animated:

Hice un prototipo para mostrarte cómo funciona.

Debido a que esto se hace con temporizadores y cosas, puede establecer cuánto tiempo durará el autoScroll y qué tan rápido (y cuán lejos, si está usando el conjunto de contenido) la animación irá.

Este es el archivo .h:

#import <UIKit/UIKit.h> @interface AutomaticTableViewScrollViewController : UIViewController <UITableViewDelegate,UITableViewDataSource> { UITableView *slotMachine; NSMutableArray *listOfItems; NSTimer *tableTimer; } @property (nonatomic,retain) UITableView *slotmachine; @property (nonatomic,retain) NSMutableArray *listOfItems; @property (nonatomic,retain) NSTimer *tableTimer; -(void)automaticScroll; -(void)stopscroll; @end

Este es el archivo .m:

#import "AutomaticTableViewScrollViewController.h" @implementation AutomaticTableViewScrollViewController @synthesize slotmachine; @synthesize listOfItems; @synthesize tableTimer; -(void)loadView { [super loadView]; slotmachine = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain]; slotmachine.delegate = self; slotmachine.dataSource = self; [self.view addSubview:slotmachine]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } // Set up the cell... if (indexPath.row % 2 == 0) { cell.textLabel.text = @"blalala"; } return cell; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 99999; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { //you might want to do this action in ur buttonTargetMethod //start timers tableTimer = [NSTimer scheduledTimerWithTimeInterval:0.2 //this value arranges the speed of the autoScroll target:self selector:@selector(automaticScroll) userInfo:nil repeats:YES]; [NSTimer scheduledTimerWithTimeInterval:5 //this arranges the duration of the scroll target:self selector:@selector(stopscroll) userInfo:nil repeats:NO]; } -(void)automaticScroll { [slotmachine setContentOffset:CGPointMake(slotmachine.contentOffset.x, slotmachine.contentOffset.y + 50) animated:YES]; //the 50 stands for the amount of movement every tick the timer will make } -(void)stopscroll { //stop tabletimer again [tableTimer invalidate]; } -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation { return YES; } @end

Si tiene alguna pregunta, no dude en dejar un comentario y se lo explicaré.


He estado usando las funciones de interpolación del marco Sparrow para hacer animaciones similares.

El enlace de arriba tiene un ejemplo de cómo configurarlo. Puede animar cualquier propiedad numérica de cualquier objeto Objective C, y puede usar transiciones como "entrada fácil", "salida fácil", "facilidad en elástico", etc., o simplemente buenas animaciones lineales antiguas.

Sin embargo, la propiedad contentSize es un CGPoint , por lo que en realidad necesitaría animar una propiedad diferente en una de sus clases y luego implementar un método real para la función de establecimiento de propiedades para que actualice el contentOffset.

- (void) setTableScrollPosition:(CGFloat)position { CGPoint newOffset = CGPointMake(0.0, position); scrollView.contentOffset = newOffset; }


La forma más común de hacer aplicaciones de máquinas tragamonedas es con UIPickerView, tal vez debería verificar esto.


No puedes (a mi entender, he estado buscando por todas partes una manera de hacer esto) hacer una velocidad que no sea constante para

- scrollToRowAtIndexPath:atScrollPosition:animated:

Por lo tanto, sugiero ... que si realmente lo necesitas, UIPickerView una animación o algo así, o haz algo mucho más fácil que te ahorre tiempo, usa UIPickerView


Puede que tenga que mirar en esa dirección?

[UIView animateWithDuration: 1.0 animations: ^{ [tableViewExercises scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:previousSelectedExerciseCell inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO]; }completion: ^(BOOL finished){ } ];

Trabajar solo con animación: NO.


Si puede requerir iOS 5, puede usar el método UIScrollViewDelegate scrollViewWillEndDragging:withVelocity:targetContentOffset: Esto le permite ver qué tan rápido estaba moviendo el dedo el usuario, dónde terminaría la animación de desaceleración con la velocidad predeterminada, y le permite anular la velocidad de la animación, de modo que termine en un punto diferente.