6

Ich habe eine UICollectionView in meiner App implementiert. Mein Problem ist, dass ich eine Zelle programmatically auswählen muss (wie wenn der Benutzer darauf klopfte). Die Methode:So wählen Sie Element/Zelle von UICollectionView aus Code

- (void)selectItemAtIndexPath:(NSIndexPath *)indexPath 
        animated:(BOOL)animated 
       scrollPosition:(UICollectionViewScrollPosition)scrollPosition 

, der Teil der UICollectionView Klasse ist nicht das, was ich nennen müssen, da diese Methode nicht nennen:

- (void)collectionView:(UICollectionView *)collectionView 
     didSelectItemAtIndexPath:(NSIndexPath *)indexPath 

Es setzt nur die selected Eigenschaft der Zelle YES;

+2

Was ist mit dem Aufruf der Methode selbst, nachdem Sie Ihre Zelle ausgewählt haben? Sie könnten [self collectionView: yourView didSelectItemAtIndexPath: yourIndexPath]; –

+0

Ja. Ich habs. Vielen Dank! –

+1

Vielleicht wird diese Antwort Ihnen helfen http://stackoverflow.com/questions/13177201/select-items-programmatical-in-uicollectionview –

Antwort

7

Ich rufe [self collectionView:yourView didSelectItemAtIndexPath:yourIndexPath], um programmgesteuert eine Zelle auszuwählen. Aber in der Methode Zelle ist immer Null. Dies funktioniert sehr gut, wenn der Benutzer eine Zelle auswählt.

+7

oder in swift könnten Sie verwenden: 'collectionView.delegate? .collectionView! (CollectionView, didSelectItemAtIndexPath: someIndexPath)' – mbuff24

+0

Das funktioniert, ist es eine schlechte Übung jedoch Delegat Methoden direkt aufrufen (die Collection View sollte diese Methode auf ihre aufrufen Delegieren wie Apple empfiehlt). Da @leviathan erwähnt "[selectItemAtIndexPath: animated: scrollPosition:]" wird die Delegate-Methode nicht aufgerufen, so gibt es bessere Möglichkeiten, um das zu umgehen. – ppalancica

7

Zuerst müssen Sie die Zielzelle sichtbar machen, sonst gibt [yourCollectionView cellForItemAtIndexPath:yourIndexPath] immer nil zurück.

// scroll to the cell 
[yourCollectionView scrollToItemAtIndexPath:yourIndexPath 
          atScrollPosition:UICollectionViewScrollPositionBottom 
            animated:NO]; 

// call delegate method 
[self collectionView:yourCollectionView didSelectItemAtIndexPath:yourIndexPath]; 

// now you have selected the cell and can do anything to it in the delegate method :-) 
+0

Meine Zelle ist immer sichtbar, aber cellForItemAtIndexPath gibt immer nil zurück (auch nach Aufruf von scrollToItemAtIndexPath) –

8

Ja, das ist richtiges Verhalten. Dokumentation für [selectItemAtIndexPath:animated:scrollPosition:]says:

Diese Methode keine Auswahl bezogenen verursacht Delegatmethoden zu aufgerufen werden.

Verwandte Themen