web-dev-qa-db-fra.com

Comment puis-je changer la direction de défilement dans UICollectionView?

J'ai une application ICollectionView dans mon storyboard iOS. Lorsque l'appareil est en orientation portrait, je souhaite qu'il défile verticalement, et lorsqu'il est en paysagiste, je souhaite qu'il défile horizontalement.

Dans UICollectionView, je peux voir le membre scrollEnabled , mais je ne vois aucun moyen de définir la direction du défilement. Ai-je raté quelque chose?

36
Kenny
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];

Notez également qu'il semble correct d'appeler cela dans prepareForLayout dans votre disposition de flux ...

@interface LayoutHorizontalThings : UICollectionViewFlowLayout
@end

@implementation LayoutHorizontalBooks
-(void)prepareLayout
    {
    [super prepareLayout];

    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    self.minimumInteritemSpacing = 0;
    self.minimumLineSpacing = 0;
    self.itemSize = CGSizeMake(110,130);
    self.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }
61
user3040186

Définissez le scrollDirection du collectionViewLayout de la vue de collection.

Les documents sont ici .

13
Mundi

Vous devriez essayer ceci:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{

  UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)[self.collectionView collectionViewLayout];

  if ((toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) || (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft)){
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
  }
  else{
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
  } 
}

Dans Swift:

override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {

    var layout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout

    if ((toInterfaceOrientation == UIInterfaceOrientation.LandscapeLeft) || (toInterfaceOrientation == UIInterfaceOrientation.LandscapeRight)){

        layout.scrollDirection = UICollectionViewScrollDirection.Vertical
    }
    else{
       layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
    }

}
9
Allan Scofield

Swift 4 et 4.2

if let layout = collectionViewObj.collectionViewLayout as? UICollectionViewFlowLayout {
        layout.scrollDirection = .vertical  // .horizontal
    }
7
GSK

Félicitations à Mundi et Dan Rosenstark pour leur réponse, voici la version Swift 4.2.

if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
    flowLayout.scrollDirection = .horizontal
}
3
Travis M.

Faites cela dans votre storyboard. De l'inspecteur d'identité et sélectionnez la direction et donnez votre direction. enter image description here

1