UICollectionView desplácese automáticamente a la parte inferior cuando se cargue la pantalla


Estoy tratando de averiguar cómo desplazarse hasta la parte inferior de un UICollectionView cuando la pantalla se carga por primera vez. Puedo desplazarme hasta la parte inferior cuando se toca la barra de estado, pero me gustaría poder hacerlo automáticamente cuando la vista se cargue también. Lo siguiente funciona bien si quiero desplazarme hasta la parte inferior cuando se toque la barra de estado.

- (BOOL)scrollViewShouldScrollToTop:(UITableView *)tableView
{
NSLog(@"Detect status bar is touched.");
[self scrollToBottom];
return NO;
}

-(void)scrollToBottom
{//Scrolls to bottom of scroller
 CGPoint bottomOffset = CGPointMake(0, collectionViewReload.contentSize.height -     collectionViewReload.bounds.size.height);
 [collectionViewReload setContentOffset:bottomOffset animated:NO];
 }

He intentado llamar a [self scrollToBottom] en viewDidLoad. Esto no está funcionando. Cualquier idea sobre cómo puedo desplazarme hasta el fondo ¿cuándo se carga la vista?

Author: Firo, 2013-02-08

6 answers

Solo para explicar mi comentario.

ViewDidLoad se llama antes de que los elementos sean visuales, por lo que ciertos elementos de la interfaz de usuario no se pueden manipular muy bien. Cosas como mover botones alrededor del trabajo, pero tratar con subviews a menudo no lo hace (como desplazar una vista de colección).

La mayoría de estas acciones funcionarán mejor cuando se llamen en viewWillAppear o viewDidAppear. Aquí hay una excepción de los documentos de Apple que señala una cosa importante que hacer al anular cualquiera de estos métodos:

Puede anular este método para realizar tareas adicionales asociadas con la presentación de la vista. Si anula este método, debe llamar super en algún momento de su implementación.

La super llamada generalmente se llama antes de implementaciones personalizadas. (por lo que la primera línea de código dentro de los métodos anulados).

 16
Author: Firo,
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
2013-02-08 00:43:18

Encontré que nada funcionaría en viewWillAppear. Solo puedo hacer que funcione en viewDidLayoutSubviews:

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:endOfModel inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
}
 33
Author: Will Larche,
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-06-07 19:35:52

Así que tenía un problema similar y aquí hay otra manera de llegar a él sin usar scrollToItemAtIndexPath

Esto se desplazará hasta la parte inferior solo si el contenido es más grande que el marco de vista.

Probablemente sea mejor usar scrollToItemAtIndexPath, pero esta es solo otra forma de hacerlo.

CGFloat collectionViewContentHeight = myCollectionView.contentSize.height;
CGFloat collectionViewFrameHeightAfterInserts = myCollectionView.frame.size.height - (myCollectionView.contentInset.top + myCollectionView.contentInset.bottom);

if(collectionViewContentHeight > collectionViewFrameHeightAfterInserts) {
   [myCollectionView setContentOffset:CGPointMake(0, myCollectionView.contentSize.height - myCollectionView.frame.size.height) animated:NO];
}
 6
Author: Fazri,
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-10-21 21:06:59

Ejemplo de Swift 3

let sectionNumber = 0
self.collectionView?.scrollToItem(at: //scroll collection view to indexpath
                                  NSIndexPath.init(row:(self.collectionView?.numberOfItems(inSection: sectionNumber))!-1, //get last item of self collectionview (number of items -1)
                                                   section: sectionNumber) as IndexPath //scroll to bottom of current section
                                , at: UICollectionViewScrollPosition.bottom, //right, left, top, bottom, centeredHorizontally, centeredVertically
                                animated: true)
 5
Author: mourodrigo,
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-11-11 18:05:59

Obtener indexpath para el último elemento. Entonces...

- (void)scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(BOOL)animated
 3
Author: Hiren,
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-19 10:59:38

Para mí, encontré la siguiente solución:

Llama a reloadData en collectionView y haz que dcg en main se desplace.

 __weak typeof(self) wSelf = self;

 [wSelf.cv reloadData];
 dispatch_async(dispatch_get_main_queue(), ^{
 NSLog(@"HeightGCD:%@", @(wSelf.cv.contentSize.height));
 [wSelf.cv scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:50 inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];
 });
 3
Author: Dmitry Nelepov,
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-10-23 09:56:26