2011-01-03 9 views
6

¿Cuál es la mejor manera de implementar un UITableView cíclico donde, en lugar de mostrar espacios en blanco cuando el usuario se desplaza hasta los límites de la tabla, simplemente se envuelve cíclicamente? Los ejemplos aquí pueden ser elegir el día de la semana, la hora en un día de 24 horas o los husos horarios ordenados secuencialmente en todo el mundo. Tenga algunas ideas sobre cómo hackear esto (puede ser una lista de 100x7 días empezando desde el medio) pero nada elegante.implementando un UITableView cíclico

¿Alguien tiene alguna idea o experiencia al respecto?

David

Respuesta

-3

Usted no puede hacer la tabla cíclica. supongamos que devuelve un gran número de filas del método numberOfRowsInSection (número finito), luego también la tabla tiene un extremo superior y de cource no puede devolver infinito para el número de filas, por eso tiene un final por debajo. por lo que no puede parecer mesa redonda.

puede hacerlo para un número finito, también puede repetir las filas, pero esto no es posible para hacer tableView cíclico.

+0

Creo que esto es todo. Nada elegante para hacer aquí; al menos las filas son todas virtuales para que pueda hacerlas sobre la marcha. – drw

+0

@drw: Siga este enlace: [link] (http://stackoverflow.com/questions/5675535/how-to-implement-cyclic-scrolling-on-tableview) –

+0

Consulte mi respuesta a continuación. Tiene el código. He estado usando ese código por mucho tiempo. Funciona. –

4

He visto este comportamiento un par de veces, pero no en un UITableView era un UIPickerView. El código es bastante simple y, probablemente, convertible en un UITableView ....

el código de UIPickerView CICLIC

RollerViewController.h

@interface RollerViewController : UIViewController <UIPickerViewDelegate>{ 
    UIPickerView *picker; 
}  
@end 

RollerViewController.m

#import "RollerViewController.h" 

@implementation RollerViewController 

#define MAX_ROLL 100 
#define ROWS_COUNT 10 

#pragma mark - 
#pragma mark Helpers 

- (void) infinitePickerViewDidSelectRow:(NSInteger)row inComponent:(NSInteger)component{ 
    NSUInteger base10 = (MAX_ROLL/2) - (MAX_ROLL/2)%ROWS_COUNT; 
    [picker selectRow:row%ROWS_COUNT+base10 inComponent:component animated:FALSE]; 
} 

#pragma mark - 
#pragma mark UIPickerView dataSource delegate methods 

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView { 
    return 3; 
} 
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component { 
    return MAX_ROLL; 
} 
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{ 
    return (CGFloat)40; 
} 
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { 
    [self infinitePickerViewDidSelectRow:row inComponent:component]; 
} 

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{ 
    return (CGFloat) 50; 
} 
- (UIView *)pickerView:(UIPickerView *)thePickerView viewForRow:(NSInteger)row 
      forComponent:(NSInteger)component reusingView:(UIView *)rview { 

    UILabel *retval = (UILabel *)rview; 
    if (!retval) { 
     retval= [[[UILabel alloc] initWithFrame:CGRectMake(5,5,40,30) ] autorelease]; 
    } 

    retval.text = [NSString stringWithFormat:@"%d", row%ROWS_COUNT]; 
    retval.font = [UIFont systemFontOfSize:25]; 
    retval.textAlignment = UITextAlignmentCenter; 
    retval.backgroundColor = [UIColor clearColor]; 
    return retval; 
} 

#pragma mark overides 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, 320, 280)]; 
    picker.delegate = self; 
    [self.view addSubview:picker]; 

} 
- (void) viewDidAppear:(BOOL)animated{ 
    [super viewDidAppear:animated]; 

    [self infinitePickerViewDidSelectRow:arc4random()%MAX_ROLL inComponent:0]; 
    [self infinitePickerViewDidSelectRow:arc4random()%MAX_ROLL inComponent:1]; 
    [self infinitePickerViewDidSelectRow:arc4random()%MAX_ROLL inComponent:2]; 
} 
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { 
    return YES; 
} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
} 

- (void)dealloc { 
    [picker release]; 
    [super dealloc]; 
} 

@end 
2

Sí, es posible hacer una UITableView cíclica. Simplemente pasa un número realmente grande como el número de filas y luego, para cada fila que la vista de tabla solicita, le pasa el row_number% number_of_rows, por lo que siempre está iterando dentro de sus datos, incluso si el número de fila es ridículamente grande.

Se puede ver un ejemplo aquí: http://dev.doukasd.com/2011/04/infinite-scrolling-dial-control-for-ios/

Básicamente es como UIPickerView implementa con un UITableView.

4

UITableView es lo mismo que UIScrollView en el método scrollViewDidScroll.

Por lo tanto, es fácil emular el desplazamiento infinito.

  1. el doble de la matriz de modo que la cabeza y la cola se unen entre sí para emular mesa circular

  2. usar mi siguiente código para hacer cambio de usuario entre la primera parte de la tabla duplicado y segunda parte de la tabla duplicado cuando tienden para llegar al comienzo o al final de la mesa.

:

/* To emulate infinite scrolling... 

The table data was doubled to join the head and tail: (suppose table had 1,2,3,4) 
1 2 3 4|1 2 3 4 (actual data doubled) 
--------------- 
1 2 3 4 5 6 7 8 (visualising joined table in eight parts) 

When the user scrolls backwards to 1/8th of the joined table, user is actually at the 1/4th of actual data, so we scroll instantly (we take user) to the 5/8th of the joined table where the cells are exactly the same. 

Similarly, when user scrolls to 6/8th of the table, we will scroll back to 2/8th where the cells are same. (I'm using 6/8th when 7/8th sound more logical because 6/8th is good for small tables.) 

Thus, when user reaches 1/4th of the first half of table, we scroll to 1/4th of the second half, when he reaches 2/4th of the second half of table, we scroll to the 2/4 of first half. This is done simply by subtracting OR adding half the length of the new/joined table. 
*/ 


-(void)scrollViewDidScroll:(UIScrollView *)scrollView_ 
{ 

    CGFloat currentOffsetX = scrollView_.contentOffset.x; 
    CGFloat currentOffSetY = scrollView_.contentOffset.y; 
    CGFloat contentHeight = scrollView_.contentSize.height; 

    if (currentOffSetY < (contentHeight/8.0)) { 
    scrollView_.contentOffset = CGPointMake(currentOffsetX,(currentOffSetY + (contentHeight/2))); 
    } 
    if (currentOffSetY > ((contentHeight * 6)/ 8.0)) { 
     scrollView_.contentOffset = CGPointMake(currentOffsetX,(currentOffSetY - (contentHeight/2))); 
    } 

} 

P. S. - He usado este código en una de mis aplicaciones llamada NT Time Table (Lite). Si desea obtener la vista previa, puede consultar la aplicación: https://itunes.apple.com/au/app/nt-time-table-lite/id528213278?mt=8

Si su tabla a veces puede ser demasiado corta, al comienzo del método anterior puede agregar una lógica if para salir del método cuando el conteo de datos es para ejemplo menos de 9.

Cuestiones relacionadas