我目前正在编写一个UICollectionViewController
从服务器加载图像并将图像放入自定义UICollectionViewCells
的UICollectionView
. 为了让事情变得比现在更简单,我不从数据库中提取,我只是简单地创建一个存储在本地的图像数组。它可以工作,但由于某种原因,在我开始滚动之前,并非所有单元格都显示图像。
这是正在发生的事情的图像!
我已经阅读了一些教程,但它们都使用storyboard
......我想以编程方式编写这个。
继承人一些代码:
AppDelegate.m
:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
JSMediaCollectionController *instagram = [[JSMediaCollectionController alloc] initWithCollectionViewLayout:[UICollectionViewFlowLayout new]];
instagram.datasource = self;
self.array = [NSMutableArray array];
for (int i = 0; i < 100; i++) {
[self.array addObject:@"instant_noodle_with_egg.jpg"];
}
UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:instagram];
self.window.rootViewController = navCon;
[self.window makeKeyAndVisible];
return YES;
}
- (NSArray *)itemsToLoad
{
return [NSArray arrayWithArray:self.array];
}
JSMediaController.m
- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = NO;
// Register cell classes
[self.collectionView registerClass:[JSMediaCollectionCell class] forCellWithReuseIdentifier:reuseIdentifier];
self.showOneItemPerRow = false;
// Do any additional setup after loading the view.
}
#pragma mark <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [[self.datasource itemsToLoad] count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
JSMediaCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
[cell setImage:[UIImage imageNamed:[[self.datasource itemsToLoad] objectAtIndex:indexPath.row]]];
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"photo-frame.png"]];
return cell;
}
...
...
JSMediaCell.m
:
@interface JSMediaCollectionCell()
@property (nonatomic) UIImageView *view;
@end
@implementation JSMediaCollectionCell
- (id)initWithFrame:(CGRect)frame
{
if (!(self = [super initWithFrame:frame])) return nil;
self.view = [[UIImageView alloc] initWithFrame:self.frame];
[self.viewForBaselineLayout addSubview:self.view];
return self;
}
- (void)setImage:(UIImage *)image
{
self.view.image = image;
}
我非常感谢任何人帮助我走上正确的轨道......就像提醒......当我开始滚动时,图像被重新加载,但并非所有单元格都加载了图像subview
......只是一些。