0

我目前正在编写一个UICollectionViewController从服务器加载图像并将图像放入自定义UICollectionViewCellsUICollectionView. 为了让事情变得比现在更简单,我不从数据库中提取,我只是简单地创建一个存储在本地的图像数组。它可以工作,但由于某种原因,在我开始滚动之前,并非所有单元格都显示图像。

这是正在发生的事情的图像!

图片

我已经阅读了一些教程,但它们都使用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......只是一些。

4

1 回答 1

0

我可以看到您正在view使用self.frame.

相反,它应该是 self.view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];

我想你可以猜到哪里出了问题。!!!

框架应该写在单元格上。当子视图添加到单元格时,它会获取单元格的值origin,因此它会超出单元格的视图

于 2014-12-04T05:51:46.027 回答