UICollectionView не появляется
-
11-12-2019 - |
Вопрос
Я пытаюсь настроить UICollectionView
программно на мой взгляд, контроллер, который расширяет UIViewController
.По какой-то причине представление моей коллекции вообще не отображается.Ниже то, что у меня есть.
Почему оно не появляется?Я подключаю его к делегату и источнику данных и добавляю в качестве подпредставления в self.view
.Чего не хватает в моем коде?
В моем .h
файл:
@interface MainViewController : UIViewController
{
@private
UICollectionView *_collectionView;
NSMutableArray *_results; // data source array
}
@end
В моем .m
файл:
@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);
}
Решение
У меня есть ошибки, пытающиеся запустить ваш код, если я не изменил метод LoadView для ViewDidLoad - в соответствии с документами, которые вы не должны напрямую вызовать LoadView.Чтобы получить методы источника данных и методы делегирования для запуска, я переместил строки, устанавливающие делегат и источник данных в зависимости от того, где вы устанавливаете Self.collectionView= CollectionView
self.collectionView = collectionView;
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
. Другие советы
Твой numberOfSectionsInCollectionView:
возвращает 0
.Для просмотра коллекции с одним разделом вы должны либо вернуть 1
или просто не реализовывать этот метод.
Также я не вижу, где вы выделяете/инициализируете self.collectionView
.
В итоге я создал подкласс UICollectionViewController вместо UIViewController
и изменив метод инициализации на:
- (id)initWithCollectionViewLayout:(UICollectionViewLayout *)layout
и это сработало.
Вам только пришлось связать свой делегат вашей коллекции, и DataSource для ViewController в раскаренной доске. введите описание изображенияздесь