2014-08-30 73 views
-1

我有一個UICollectionView,我在viewDidLoad中設置並在此之後立即添加圖像。當用戶滾動到某一點我嘗試加入更多的圖像,但該集合視圖不會加載新的圖像將更多圖像添加到已經運行的UICollectionView中

我如何重裝或

#pragma mark - New Retrieve 
- (void) rwDataToPlist { 

    // Step1: Get plist file path 

    NSArray *sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,NSUserDomainMask, YES); 

    NSString *documentsDirectory = [sysPaths objectAtIndex:0]; 

    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"news.plist"]; 

    NSLog(@"Plist File Path: %@", filePath); 

    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { 

     stuff = [[NSArray alloc] initWithContentsOfFile:filePath]; 
     //NSLog(@"Stuff %@", stuff); 
     [self sortRetrievedData]; 
    } else { 


    } 


} 

-(void)sortRetrievedData { 
    titles = [stuff valueForKey:kKeyTitle]; 
    thumbMediaUrl = [stuff valueForKey:kKeyThumbUrl]; 
    thumbWidth = [stuff valueForKey:kKeyThumbWidth]; 
    thumbHeight = [stuff valueForKey:kKeyThumbHeight]; 

    for(NSArray *array in titles) { 
     for (NSArray *realArray in array) { 
      titles = realArray; 
     } 
    } 
    for(NSArray *array in thumbMediaUrl) { 
     for(NSDictionary *dict in array) { 
      thumbMediaUrl = dict; 
     } 
    } 
    for(NSArray *array in thumbWidth) { 
     for(NSDictionary *dict in array) { 
      thumbWidth = dict; 
     } 
    } 
    for(NSArray *array in thumbHeight) { 
     for(NSDictionary *dict in array) { 
      thumbHeight = dict; 
     } 
    } 
} 

#pragma mark - Collection View 
#pragma mark - Display Collection 
-(void)displayCollection { 
    UIColor *myColor = [UIColor colorWithRed:(245.0/255.0) green:(245.0/255.0) blue:(245.0/255.0) alpha: 1]; 

    CGRect screenBound = [[UIScreen mainScreen] bounds]; 
    CGSize screenSize = screenBound.size; 
    CGFloat screenWidth = screenSize.width; 
    CGFloat screenHeight = screenSize.height; 
    self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
    CGRect locOfScree = CGRectMake(0, 64, screenWidth, screenHeight - 44); 

    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init]; 
    imageDisplayer = [[UICollectionView alloc] initWithFrame:locOfScree collectionViewLayout:layout]; 
    [imageDisplayer setDataSource:self]; 
    [imageDisplayer setDelegate:self]; 

    UINib *nib = [UINib nibWithNibName:@"CollectionViewCell" bundle:nil]; 
    [imageDisplayer registerNib:nib forCellWithReuseIdentifier:CellIdentifier]; 
    [imageDisplayer setBackgroundColor:myColor]; 

    [self.view insertSubview:imageDisplayer belowSubview:navBar]; 
    //[self.view addSubview:imageDisplayer]; 
} 

#pragma mark - Setup 

- (void)setupData 
{ 
    self.imageURLStrings = [NSMutableArray array]; 

    // Save image to docs directory so we can get a nice URL 
    // Not sure how to get the URL from an asset catalog off the top of my head 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"greyBurger.png"]; 

    UIImage *image = [UIImage imageNamed:@"greyBurger"]; 
    NSData *data = UIImagePNGRepresentation(image); 
    [data writeToFile:path atomically:YES]; 

    // Populate our imageURLStrings array with many paths 

    for (NSInteger i = 0; i < NumberOfImages; i++) 
    { 
     [self.imageURLStrings addObject:path]; 
     //NSLog(@"Path %@", path); 
    } 
} 

- (void)setupCollectionView 
{ 
    UINib *nib = [UINib nibWithNibName:@"CollectionViewCell" bundle:nil]; 
    [self.collectionView registerNib:nib forCellWithReuseIdentifier:CellIdentifier]; 
} 

#pragma mark - UICollectionView Datasource 

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section 
{ 
    //return [self.imageURLStrings count]; 
    return [titles count]; 
    //return 2; 

} 



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CollectionViewCell *cell = (CollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath]; 


    //NSLog(@"CELL FOR COUNT:%lu", [titles count]); 
    NSString *title = [titles objectAtIndex:indexPath.row]; 
    cell.backgroundColor = [UIColor whiteColor]; 
    NSString *imageUrl = [thumbMediaUrl objectForKey:title]; 
    NSURL *thumbUrl = [NSURL URLWithString:imageUrl]; 
    UIImageView *imageView = [[UIImageView alloc] init]; 
    NSData *imageData = [NSData dataWithContentsOfURL:thumbUrl]; 
    imageView.image = [UIImage imageWithData:imageData]; 

    cell.backgroundView = imageView; 
    cell.layer.shouldRasterize = YES; 
    cell.layer.rasterizationScale = [UIScreen mainScreen].scale; 
    //cell.frame = CGRectMake(0, 0, 100, 100); 

    //cell.imageURLString = [self.imageURLStrings objectAtIndex:indexPath.item]; 

    return cell; 
} 

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CGRect screenBound = [[UIScreen mainScreen] bounds]; 
    CGSize screenSize = screenBound.size; 
    CGFloat screenWidth = screenSize.width; 

    NSString *title = [titles objectAtIndex:indexPath.row]; 
    float width = [[thumbWidth objectForKey:title] floatValue]; 
    float height = [[thumbHeight objectForKey:title] floatValue]; 
    float imageWidth = (screenWidth/2) - 3; 
    float scale = imageWidth/width; 
    float imageHeight = height * scale; 
    CGSize imageSize = CGSizeMake(imageWidth, imageHeight); 


    return imageSize; 
} 
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section { 
    return 2.0; 
} 

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section { 
    return 2.0; 
} 

// Layout: Set Edges 
- (UIEdgeInsets)collectionView: 
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section { 
    // return UIEdgeInsetsMake(0,8,0,8); // top, left, bottom, right 
    return UIEdgeInsetsMake(0,0,0,0); // top, left, bottom, right 
} 

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect 
{ 
    NSArray* attributesToReturn = [self layoutAttributesForElementsInRect:rect]; 
    for (UICollectionViewLayoutAttributes* attributes in attributesToReturn) 
    { 
     if (nil == attributes.representedElementKind) 
     { 
      NSIndexPath* indexPath = attributes.indexPath; 
      attributes.frame = [self layoutAttributesForItemAtIndexPath:indexPath].frame; 
     } 
    } 
    return attributesToReturn; 
} 

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionViewLayoutAttributes* currentItemAttributes = [self layoutAttributesForItemAtIndexPath:indexPath]; 

    if (indexPath.item < numColumns){ 
     CGRect f = currentItemAttributes.frame; 
     f.origin.y = 0; 
     currentItemAttributes.frame = f; 
     return currentItemAttributes; 
    } 
    NSIndexPath* ipPrev = [NSIndexPath indexPathForItem:indexPath.item-numColumns inSection:indexPath.section]; 
    CGRect fPrev = [self layoutAttributesForItemAtIndexPath:ipPrev].frame; 
    CGFloat YPointNew = fPrev.origin.y + fPrev.size.height + 10; 
    CGRect f = currentItemAttributes.frame; 
    f.origin.y = YPointNew; 
    currentItemAttributes.frame = f; 
    return currentItemAttributes; 
} 

我已經改變了添加更多圖片到我的滾動視圖我的代碼基於前兩個答案的建議,現在我必須將圖像添加到正在運行的視圖中。並且使每列都有自己獨立的高度所以在每個邊緣2px的間距,這就是我試圖重新載入數據

-(void)refreshView { 


    [self rwDataToPlist]; 
    [self.collectionView reloadData]; 
    [self setupCollectionView]; 
} 
+0

如果我是你,我會用一個UITableView代替它,而不是d實現「正常」無限滾動過程。使用自定義單元格的表格視圖可以處理滾動/內容大小/框架問題,如果您自己完成所有這些工作,則必須處理這些問題。 – Mike 2014-09-02 21:57:30

+0

@inVINCEable您需要輸入CollectionView底部意味着您將添加一些數據嗎? – PREMKUMAR 2014-09-03 11:32:27

+0

引用編輯2:你的'thumbMediaUrl'從哪裏來?它是一個模型或字典實際上有一個屬性(在運行時)正確的名稱爲'title'? – schmubob 2014-09-05 17:20:12

回答

2

隨着啓動iOS6本身Apple推出了UICollectionView。您可以使用UICollectionView和Pull to Bottom Refresh來實現目標。它看起來像UITableView拉到底部刷新。

這裏有一些參考的UIcollectionView:

Source Code

  1. Beginning UICollectionView
  2. UICollectionView with StoryBoard

一旦你創建UICollectionView然後你需要添加PulltoBottom刷新爲您UICollectionView像下面的代碼:

-(void)viewWillAppear:(BOOL)animated 
{ 

[self.collectionView.infiniteScrollingView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite]; 
[self.collectionView addInfiniteScrollingWithActionHandler:^{ 
    ////(@"Infinitescroll"); 







    @try { 
     int64_t delayInSeconds = 2.0; 
     dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); 
     dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ 
      //[self.dataSource addObjectsFromArray:tmp]; 
      [self.collectionView performBatchUpdates:^{ 


      } completion:nil]; 
      [self.collectionView.infiniteScrollingView stopAnimating]; 
     }); 
    } 
    @catch (NSException *exception) { 

    } 





}]; 

[super viewWillAppear:animated]; 
} 

下面的代碼,你必須添加一些文件:

SVPulltoReferesh Link

+0

UICollectionView接近我所尋找的,唯一的問題是,如果我有兩個項目並排(單獨列同一行),一個是50px高,另一個100px高,該行的高度是100px高。我希望它是動態的,所以每一列都有獨立的高度 – inVINCEable 2014-09-04 15:20:17

+0

雅你可以做到這一點。它可以在code4app.net請參考這個你可以得到很多可定製的UICollectionView – PREMKUMAR 2014-09-04 15:40:35

+0

這是一種固有的不安全的方法(代碼明智的,不是說如果UICollectionView是你需要的)。首先,您對運行時條件使用異常,而不是與程序員相關的錯誤。這不是Obj-C的方式,如果你在運行時拋出一個異常,很可能你已經做了一些可怕的事情。 [鏈接](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Exceptions/Exceptions.html)。其次,你將自己鎖定在一個固定的時間,這可能會使蘋果的閒暇時間從發佈變爲釋放。 – schmubob 2014-09-05 17:17:14

1

一些建議/問題:

  1. 不知道的你的特定問題的限制,這聽起來像你試圖展示一些圖像網格的表象,並且當用戶滾動超過特定點時加載圖像的「下一頁」。這看起來像一個UITableView或UICollectionView將是一個更合適的機制來做你想做的事情。這兩個類都會處理延遲加載的圖像,通過正確配置的數據源進行分頁,自動調整內容大小,並且在沒有mainThread凍結的情況下將快速實現。他們也基於MVC設計模式,並可能會澄清上述代碼中的一些設計。

  2. 加載更多圖像時UI /滾動凍結的原因可能是由於從磁盤讀取了userDefaults和圖像數據本身。磁盤操作可能很昂貴,特別是一次很多。如果您必須以這種方式加載元數據和圖像文件,請考慮通過GCD的dispatch_async在後臺線程上執行此處理。

  3. 第二組圖像沒有出現的原因可能是由於圖像幀或scrollView contentSize錯誤計算。考慮通過向scrollView而不是UIImageView添加一系列彩色UIViews來調試,並考慮將contentSize.height硬編碼爲比您需要的大得多的東西。此外,你有NSLog的圖像幀和contentSize,以確保他們匹配?

編輯:

下面是一個使用UICollectionView並從磁盤讀取的UIImage數據後臺線程快速示例項目的鏈接(這是不是真的有必要再因使用UICollectionView):

https://github.com/alfiehanssen/SOImageGrid

讓我知道,如果你有任何問題,希望我不完全沒譜在你的目標條款。

+0

讓我實施它,讓你知道它是如何工作的/如果它是一個合適的解決方案 – inVINCEable 2014-09-02 21:55:45

+0

我不喜歡整個固定系統,但我重寫了我的保存系統以創建更快的加載。有沒有辦法讓它動態如何我在scrollview中它? – inVINCEable 2014-09-03 02:14:08

+0

「固定系統」是什麼意思? collectionView和tableView類專門用於動態加載內容信息和scrollView(它們都建立在scrollView之上)。您可以在我的示例中修改'setupData'方法來加載您的自定義數據。您可以修改collectionView數據源實現來加載數據的後續「頁面」。除非有特定的原因,否則UICollectionView和UITableView正是你正在尋找的... – 2014-09-03 02:23:32

-2

我用UICollectionView作爲前兩個答案建議並添加CHTCollectionViewWaterfallLayout它能夠實現圖像間距我想

我的代碼:

#pragma mark - Collection View 
#pragma mark - Display Collection 
-(void)displayCollection { 
    UIColor *myColor = [UIColor colorWithRed:(245.0/255.0) green:(245.0/255.0) blue:(245.0/255.0) alpha: 1]; 

    CGRect screenBound = [[UIScreen mainScreen] bounds]; 
    CGSize screenSize = screenBound.size; 
    CGFloat screenWidth = screenSize.width; 
    CGFloat screenHeight = screenSize.height; 
    self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
    CGRect locOfScree = CGRectMake(0, 44, screenWidth, screenHeight - 44); 

    CHTCollectionViewWaterfallLayout *layout = [[CHTCollectionViewWaterfallLayout alloc] init]; 

    layout.sectionInset = UIEdgeInsetsMake(2, 2, 2, 2); 
    layout.headerHeight = 0; 
    layout.footerHeight = 0; 
    layout.minimumColumnSpacing = 2; 
    layout.minimumInteritemSpacing = 2; 
    //UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init]; 
    imageDisplayer = [[UICollectionView alloc] initWithFrame:locOfScree collectionViewLayout:layout]; 
    imageDisplayer.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; 

    [imageDisplayer setDataSource:self]; 
    [imageDisplayer setDelegate:self]; 

    UINib *nib = [UINib nibWithNibName:@"CollectionViewCell" bundle:nil]; 
    [imageDisplayer registerNib:nib forCellWithReuseIdentifier:CellIdentifier]; 
    [imageDisplayer setBackgroundColor:myColor]; 

    [self.view insertSubview:imageDisplayer belowSubview:navBar]; 
    //[self.view addSubview:imageDisplayer]; 

    imageDisplayer = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout]; 
    imageDisplayer.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; 
    imageDisplayer.dataSource = self; 
    imageDisplayer.delegate = self; 
    imageDisplayer.backgroundColor = [UIColor whiteColor]; 
    [imageDisplayer registerClass:[CHTCollectionViewWaterfallCell class] 
     forCellWithReuseIdentifier:CellIdentifier]; 
} 

#pragma mark - Setup 
- (void)setupCollectionView 
{ 
    UINib *nib = [UINib nibWithNibName:@"CollectionViewCell" bundle:nil]; 
    [self.collectionView registerNib:nib forCellWithReuseIdentifier:CellIdentifier]; 
} 

#pragma mark - UICollectionView Datasource 

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section 
{ 
    //return [self.imageURLStrings count]; 
    return [titles count]; 
    //return 2; 

} 



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    /* 
    CollectionViewCell *cell = (CollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath]; 
    */ 
    CHTCollectionViewWaterfallCell *cell = 
    (CHTCollectionViewWaterfallCell *)[collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier 
                       forIndexPath:indexPath]; 

    NSString *title = [titles objectAtIndex:indexPath.row]; 
    cell.backgroundColor = [UIColor whiteColor]; 
    NSString *imageUrl = [thumbMediaUrl objectForKey:title]; 
    NSURL *thumbUrl = [NSURL URLWithString:imageUrl]; 
    UIImageView *imageView = [[UIImageView alloc] init]; 
    NSData *imageData = [NSData dataWithContentsOfURL:thumbUrl]; 
    imageView.image = [UIImage imageWithData:imageData]; 

    cell.backgroundView = imageView; 
    cell.layer.shouldRasterize = YES; 
    cell.layer.rasterizationScale = [UIScreen mainScreen].scale; 
    return cell; 

} 

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CGRect screenBound = [[UIScreen mainScreen] bounds]; 
    CGSize screenSize = screenBound.size; 
    CGFloat screenWidth = screenSize.width; 

    NSString *title = [titles objectAtIndex:indexPath.row]; 
    float width = [[thumbWidth objectForKey:title] floatValue]; 
    float height = [[thumbHeight objectForKey:title] floatValue]; 
    float imageWidth = (screenWidth/2) - 3; 
    float scale = imageWidth/width; 
    float imageHeight = height * scale; 
    CGSize imageSize = CGSizeMake(imageWidth, imageHeight); 


    return imageSize; 
} 
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section { 
    return 2.0; 
} 

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section { 
    return 2.0; 
} 

// Layout: Set Edges 
- (UIEdgeInsets)collectionView: 
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section { 
    // return UIEdgeInsetsMake(0,8,0,8); // top, left, bottom, right 
    return UIEdgeInsetsMake(0,0,0,0); // top, left, bottom, right 
} 

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect 
{ 
    NSArray* attributesToReturn = [self layoutAttributesForElementsInRect:rect]; 
    for (UICollectionViewLayoutAttributes* attributes in attributesToReturn) 
    { 
     if (nil == attributes.representedElementKind) 
     { 
      NSIndexPath* indexPath = attributes.indexPath; 
      attributes.frame = [self layoutAttributesForItemAtIndexPath:indexPath].frame; 
     } 
    } 
    return attributesToReturn; 
} 

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionViewLayoutAttributes* currentItemAttributes = [self layoutAttributesForItemAtIndexPath:indexPath]; 

    if (indexPath.item < numColumns){ 
     CGRect f = currentItemAttributes.frame; 
     f.origin.y = 0; 
     currentItemAttributes.frame = f; 
     return currentItemAttributes; 
    } 
    NSIndexPath* ipPrev = [NSIndexPath indexPathForItem:indexPath.item-numColumns inSection:indexPath.section]; 
    CGRect fPrev = [self layoutAttributesForItemAtIndexPath:ipPrev].frame; 
    CGFloat YPointNew = fPrev.origin.y + fPrev.size.height + 10; 
    CGRect f = currentItemAttributes.frame; 
    f.origin.y = YPointNew; 
    currentItemAttributes.frame = f; 
    return currentItemAttributes; 
} 
+0

把這個問題稱爲你投下我的答案(大概是爲了不放棄賞金)並接受你的答案,這顯然是建立在我提出的建議上的。不酷。 – 2014-09-08 15:27:09

相關問題