2012-10-09 30 views
6

Estoy tratando de implementar el UIRefreshControl en mi aplicación. Tengo un archivo xib y agregué un UITableViewController al archivo de punta vacía y establecí la propiedad de actualización en "habilitada". También agregué código al viewDidLoad y un método de actualización personalizado. El problema es que tengo un error que no puedo encontrar ninguna información sobre .... en mi viewDidLoad consigo "Propiedad 'refreshControl' no se encuentra en objeto de tipo ViewController"UIRefreshControl issues

- (void)viewDidLoad{ 

[super viewDidLoad]; 

self.myTableView = 
[[UITableView alloc] initWithFrame:self.view.bounds 
          style:UITableViewStyleGrouped]; 

self.myTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | 
            UIViewAutoresizingFlexibleHeight; 

self.myTableView.delegate = self; 
self.myTableView.dataSource = self; 

[self.view addSubview:self.myTableView]; 

UIRefreshControl *refresh = [[UIRefreshControl alloc] init]; 

refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"Pull to Refresh"]; 
[refresh addTarget:self action:@selector(refreshView:) forControlEvents:UIControlEventValueChanged]; 

self.refreshControl = refresh; 

} 

-(void)refreshView:(UIRefreshControl *)refresh { 

refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"Refreshing data..."]; 

// custom refresh logic would be placed here... 

NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"MMM d, h:mm a"]; 
NSString *lastUpdated = [NSString stringWithFormat:@"Last updated on %@", 
           [formatter stringFromDate:[NSDate date]]]; 

refresh.attributedTitle = [[NSAttributedString alloc] initWithString:lastUpdated]; 
[refresh endRefreshing]; 

} 

no tengo ni idea de por qué la propiedad no está disponible ... ¿Qué me estoy perdiendo?

Parece que necesito heredar de UITableViewController en mi archivo ViewController.h. Si ya tengo UITableView, ¿cómo heredo de ambos? Si cambio de código ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>-ViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource> entonces consigo un error:

error: NSInternalInconsistencyException', 
    reason: '-[UITableViewController loadView] loaded the "ViewController_iPhone" nib but didn't get a UITableView.' 

Respuesta

11

Puedes añadir UIRefreshControl como subvista a su UITableView.

UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init]; 
[refreshControl addTarget:self action:@selector(handleRefresh:) forControlEvents:UIControlEventValueChanged]; 
[self.myTableView addSubview:refreshControl]; 

Según comentario de Dave, esto puede romper en futuras versiones de iOS. Por lo tanto, tenga cuidado al usar esto y trate de plantear un bug report to apple con respecto a esto.

Actualización: Un mejor enfoque es mediante la adición de UITableViewController como ChildViewController de self y luego añadiendo tableViewController.tableView como la subvista de self.view. No tienes que hacer ningún truco para que funcione de esta manera.

[self addChildViewController:tableViewController]; 
[self.view addSubview:tableViewController.tableView]; 

Se puede definir el marco para tableView en consecuencia. Usando este enfoque, UIRefreshControl debería funcionar de la misma manera que funciona para UITableViewController. `

+3

Esto no es compatible y puede fallar en la versión futura de iOS. La única forma admitida de usar un 'UIRefreshControl' es con un' UITableViewController'. –

+1

@ACB, eso es exactamente lo que necesitaba !!! Gracias a millones. ¡Ojalá pudiera darte más accesorios! – brianhevans

+1

Sí, puede tener un UIRefreshControl en una clase UIViewController con una UITableView y que agregó manualmente. Los comentarios de otras respuestas pueden ser ciertos (no va con los documentos), pero este pequeño truco funciona en iOS6. –

1

Su clase ViewController debe ser una subclase de UITableViewController con el fin de tener acceso a la propiedad refreshControl.

+0

Podemos agregar 'UITableViewController' como un controlador de vista hijo y luego agregar' tableview' como una subvista de 'self.view' del controlador de vista actual, ¿verdad? Me preguntaba si realmente necesitamos una subclase. – iDev

+0

@ACB Sí, puede usar un 'UITableViewController' como controlador de vista secundaria. Ese es un excelente enfoque. –

+0

Gracias por confirmar. Estaba confundido con esta afirmación en su respuesta *** "La clase ViewController debe ser una subclase de UITableViewController" ***, ya que también podemos agregarla como una subvista. – iDev

5

Lo que debe recordar:

  • UIRefreshControl sólo para UITableViewController, por lo que su clase debe ser la subclase de UITableViewController.

  • UITableViewController tiene una propiedad refreshControl, debe asignar un UIRefreshControl y ponerlo a esa propiedad.

Ex:

UITableViewController *tableViewController = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain]; 

UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init]; 

[refreshControl addTarget:self action:@selector(refreshControlAction:) forControlEvents:UIControlEventValueChanged]; 

tableViewController.refreshControl = refreshControl; 
+0

Esta es la respuesta correcta. Agregarlo manualmente al 'UITableView' según la respuesta aceptada podría causar un comportamiento inesperado en futuras versiones de iOS. – Samah

0

lo recomiendo a hacer por separado UITableViewController Subclase de myTableView. Y luego usando addChildviewController o iOS6 ContainerView para agregar esa clase dentro de ViewController original. De esa forma, incluso en la parte de Vista, puede usar UIRefreshControl.

La respuesta aceptada no es oficial, por lo que podría romperse en futuras versiones, como decía el comentario ...

2

Todas estas son formas complejas de hacer algo simple.

No necesita agregar un control de actualización, o declarar uno en su viewController. Agregar pull-to-refresh es un proceso de dos pasos.
Paso 1: en su guión gráfico, vaya a su tabla ViewController y, donde dice "Actualizar", seleccione "Activado".
Paso 2: Añadir el siguiente código a su archivo tableViewController.m, en viewDidLoad:

[self.refreshControl addTarget:self 
          action:@selector(refresh) 
        forControlEvents:UIControlEventValueChanged]; 

Eso es todo el proceso, aparte de hacer cosas en su método -actualizar. Cuando desee que deje de refrescarse, llame al [self.refreshControl endRefreshing];.

+0

¡Gracias! Tenía la sensación de que todos los tutoriales que estaba leyendo eran demasiado complicados. –