Pregunta

Estoy intentando configurar UICollectionView programáticamente en mi controlador de vista que se extiende UIViewController.Por alguna razón, la vista de mi colección no aparece en absoluto.A continuación se muestra lo que tengo.

¿Por qué no aparece?Lo estoy conectando al delegado y a la fuente de datos y lo estoy agregando como una subvista a self.view.¿Qué falta en mi código?

En mi .h archivo:

@interface MainViewController : UIViewController
{
    @private
    UICollectionView *_collectionView;
    NSMutableArray *_results; // data source array
}
@end

En mi .m archivo:

@interface MainViewController () <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) NSMutableArray *results;
@end

@implementation MainViewController

@synthesize collectionView = _collectionView;
@synthesize results = _results;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // some init stuff - nothing to do with collection view.
    }

    return self;
}

- (void)loadView
{
    self.results = [NSMutableArray array];
    UIImage *image1 = [UIImage imageNamed:@"img1.jpg"];
    UIImage *image2 = [UIImage imageNamed:@"img2.jpg"];
    [self.results addObject:image1];
    [self.results addObject:image2];

    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];

    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:flowLayout];
    self.collectionView = collectionView;

    [self.view addSubview:self.collectionView];

    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"Cell"];
    [self.collectionView reloadData];

}

- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section
{
    return [self.results count];
}

- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView
{
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithPatternImage:[self.results objectAtIndex:indexPath.row]];
    return cell;
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    UIImage *image = [self.results objectAtIndex:indexPath.row];    
    return CGSizeMake(image.size.width, image.size.height);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(50, 20, 50, 20);
}
¿Fue útil?

Solución

Recibí errores al intentar ejecutar su código a menos que cambiara el método loadView a viewDidLoad; según los documentos, se supone que no debe llamar directamente a loadView.Para que se ejecuten los métodos de fuente de datos y delegado, moví las líneas que configuran el delegado y la fuente de datos en self debajo de donde configuraste self.collectionView = collectionView

    self.collectionView = collectionView;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;

Otros consejos

Su numberOfSectionsInCollectionView: devoluciones 0.Para una vista de colección con una sección, debe regresar 1 o simplemente no implementar este método.

Tampoco puedo ver dónde asignaste/init self.collectionView.

Terminé subclasificando UICollectionViewController en lugar de UIViewController y cambiando el método init a:

- (id)initWithCollectionViewLayout:(UICollectionViewLayout *)layout

Y funcionó.

Solo tenía que vincular su delegado CollectionView y dataSource a ViewController en StoryBoard.ingrese la descripción de la imagen aquí

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top