2015-11-13 233 views
1

我正在使用UICollectionView,我有一個主類和另一個是UICollectionViewFlowLayout的子類。就是這個單元格的寬度和高度在主類中是0.在子類中,單元格的大小是合適的。UICollectionViewCell寬度和高度0

下面是一些代碼: 的FlowLayoutSubClass

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

if (!currentItemAttributes) { 
    currentItemAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath]; 
} 

CGFloat containerWidth = self.collectionView.frame.size.width; 
CGFloat cellWidth = containerWidth/2.0f - 1.0f; 
CGFloat baseHeight = containerWidth/4.0f; 


CGRect frame = [self frameForIndexPath:indexPath]; 
if (CGRectEqualToRect(frame, CGRectZero)) { 
    ArtworkModel *currentObject = [self.artworksArray objectAtIndex:indexPath.row]; 
    CGFloat height = currentObject.height; 
    frame.origin = [self getNextFreePosition]; 
    frame.size.width = cellWidth; 
    frame.size.height = 120 + arc4random() % (200 - 120); 
    [self saveFrame:frame forIndexPath:indexPath]; 
    [self saveFrame:frame]; 
} 

currentItemAttributes.frame = frame; 
currentItemAttributes.size = frame.size; 


return currentItemAttributes; 
} 
- (CGRect)frameForIndexPath:(NSIndexPath *)indexPath { 
CGRect frame = CGRectZero; 
NSString *key = [NSString stringWithFormat:@"%ld-%ld", (long)indexPath.section, (long)indexPath.row]; 
NSString *frameString = [self.framesByIndexPath objectForKey:key]; 
if (frameString) { 
    frame = CGRectFromString(frameString); 
} 
return frame; 
} 

- (void)saveFrame:(CGRect)frame forIndexPath:(NSIndexPath *)indexPath { 
if (!self.framesByIndexPath) { 
    self.framesByIndexPath = [[NSMutableDictionary alloc] init]; 
} 
NSString *key = [NSString stringWithFormat:@"%d-%d", indexPath.section, indexPath.row]; 
[self.framesByIndexPath setObject:NSStringFromCGRect(frame) forKey:key]; 
} 

- (CGPoint)getNextFreePosition { 
CGFloat containerWidth = self.collectionView.frame.size.width; 
CGFloat cellWidth = containerWidth/2.0f; 

CGPoint point = CGPointZero; 

NSArray *leftFrames = [self.framesDictionary valueForKey:@"left"]; 
NSArray *rightFrames = [self.framesDictionary valueForKey:@"right"]; 

NSString *lastLeftFrameString = [leftFrames lastObject]; 
NSString *lastRightFrameString = [rightFrames lastObject]; 
if (lastLeftFrameString == nil) { 
    // There is no frame saved yet, so this will be the first 
    point.x = 0.0f; 
    point.y = 0.0f; 
} else { 
    if (lastRightFrameString == nil) { 
     // There is no item on the right side 
     point.x = cellWidth; 
     point.y = 0.0f; 
    } else { 
     // There are items on both left and right sides... 
     // Check which one has the smallest Y component 
     CGRect leftFrame = CGRectFromString(lastLeftFrameString); 
     CGRect rightFrame = CGRectFromString(lastRightFrameString); 
     if (CGRectGetMaxY(leftFrame) <= CGRectGetMaxY(rightFrame)) { 
      // We put this one on the left 
      point.x = 0.0f; 
      point.y = CGRectGetMaxY(leftFrame); 
     } else { 
      point.x = cellWidth; 
      point.y = CGRectGetMaxY(rightFrame); 
     } 
    } 
} 
return point; 
} 

- (void)saveFrame:(CGRect)frame { 
if (!self.framesDictionary) { 
    self.framesDictionary = [[NSMutableDictionary alloc] init]; 
} 
NSString *sideKey = nil; 
if (CGRectGetMinX(frame) == 0.0f) { 
    // left 
    sideKey = @"left"; 
} else { 
    sideKey = @"right"; 
} 
NSMutableArray *frames = [self.framesDictionary objectForKey:sideKey]; 
if (!frames) { 
    frames = [[NSMutableArray alloc] init]; 
    [self.framesDictionary setObject:frames forKey:sideKey]; 
} 
[frames addObject:NSStringFromCGRect(frame)]; 
} 
@end 

和主類:

- (void)takeAllArtworks { 
[WaitingView showWaitingView:shadowView WithIndicator:indicatorActivity]; 
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
NSMutableString *requestURL = [[NSMutableString alloc] init]; 
[requestURL appendFormat:@"%@%@", BASE_URL_ARTWORK, GET_ARTWORKS]; 

// NSInteger screenWidth = self.view.frame.size.width/2.0f; 
[manager GET:requestURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { 
    if ([[responseObject objectForKey: @"status"] integerValue] == 0) { 
     NSArray *artworks = [responseObject objectForKey:@"Data"]; 
     if ([artworks count] > 0) { 
      for (NSDictionary *dict in artworks) { 
       ArtworkModel *artwork = [[ArtworkModel alloc] init]; 
       if ([dict objectForKey:@"Title"] != [NSNull null]) { 
        artwork.title = [dict objectForKey:@"Title"]; 
       } 
       if ([dict objectForKey:@"Description"] != [NSNull null]) { 
        artwork.descriptionAlbum = [dict objectForKey:@"Description"]; 
       } 
       if ([dict objectForKey:@"ArtistName"] != [NSNull null]) { 
        artwork.artistName = [dict objectForKey:@"ArtistName"]; 
       } 

       NSString *dateAdded = [[dict objectForKey:@"DateAdded"] substringWithRange:NSMakeRange(0, 19)]; 
       NSString *dateUpdated = [[dict objectForKey:@"DateUpdated"] substringWithRange:NSMakeRange(0, 19)]; 

       NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
       [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"]; 
       NSDate *dateAd = [formatter dateFromString:dateAdded]; 
       NSDate *dateUp = [formatter dateFromString:dateUpdated]; 

       NSString *result; 

       if ([dateAd compare:dateUp] == NSOrderedAscending) { 
        result = [NSString stringWithFormat:@"edited %@", [self relativeDateStringForDate:dateUp]]; 
       } else { 
        result = [self relativeDateStringForDate:dateAd]; 
       } 

       artwork.dateAdded = result; 

       if ([dict objectForKey:@"MediaItems"] != [NSNull null]) { 
        NSArray *mediaArray = [dict objectForKey:@"MediaItems"]; 

        if ([mediaArray count] > 0) { 
         for (NSDictionary *mediaDict in mediaArray) { 
//        NSString *endpoint = [NSString stringWithFormat:@"%@.ashx?w=%ld&h=%d&mode=crop", [mediaDict objectForKey:@"Url"], (long)screenWidth, 170]; 
          NSString *endpoint = [mediaDict objectForKey:@"Url"]; 
          NSString *imageURL = [NSString stringWithFormat:@"%@%@", IMAGE_BASE_URL, endpoint]; 
          NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]; 
          [artwork.imageUrls addObject:[UIImage imageWithData:data]]; 

         } 
        } 
       } 

       [listOfArtworks addObject:artwork]; 
      } 

      FBFlowLayout *layout = [[FBFlowLayout alloc] initWithArtworks:listOfArtworks]; 
      [layout setMinimumInteritemSpacing:0.5f]; 
      [layout setMinimumLineSpacing:0.5f]; 
      layout.scrollDirection = UICollectionViewScrollDirectionVertical; 

      [artworkCollectionView reloadData]; 

      artworkCollectionView.collectionViewLayout = layout; 

      [WaitingView hideWaitingView:shadowView WithIndicator:indicatorActivity]; 
     } else { 
      [WaitingView hideWaitingView:shadowView WithIndicator:indicatorActivity]; 
     } 
    } 
    else 
     [WaitingView hideWaitingView:shadowView WithIndicator:indicatorActivity]; 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSLog(@"Faild"); 
    [WaitingView hideWaitingView:shadowView WithIndicator:indicatorActivity]; 
}]; 

} 

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { 
return [listOfArtworks count]; 
} 

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ 
FBWorkartCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WorkartCollection" forIndexPath: indexPath]; 

ArtworkModel *artworkModel = (ArtworkModel *)[listOfArtworks objectAtIndex:indexPath.row]; 
cell.nameAlbumLabel.text = artworkModel.title; 
cell.nameArtistLabel.text = artworkModel.artistName; 

if ([artworkModel.imageUrls count] > 0) { 
    cell.coverAlbumPhoto.image = [artworkModel.imageUrls objectAtIndex:0]; 
} 

cell.shadowView.alpha = 0.9; 
cell.dateLabel.text = artworkModel.dateAdded; 

CGFloat hue = (arc4random() % 256/256.0); // 0.0 to 1.0 
CGFloat saturation = (arc4random() % 128/256.0) + 0.5; // 0.5 to 1.0, away from white 
CGFloat brightness = (arc4random() % 128/256.0) + 0.5; // 0.5 to 1.0, away from black 
UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1]; 

cell.backgroundColor = color; 
return cell; 
} 

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { 
ArtworkModel *artworkModel = (ArtworkModel *)[listOfArtworks objectAtIndex:indexPath.row]; 

FBWorkDetailsViewController *dvc = [[FBWorkDetailsViewController alloc] initWithArtwork:artworkModel]; 
FBLeftMenuViewController *left = [[FBLeftMenuViewController alloc] init]; 
MFSideMenuContainerViewController *container = [MFSideMenuContainerViewController 
               containerWithCenterViewController: dvc 
               leftMenuViewController: left 
               rightMenuViewController:nil 
               withHeader: YES]; 
[container.titleLabel setText:@"WORK DETAILS"]; 
[self.navigationController pushViewController: container animated: YES]; 
} 


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { 

return [collectionViewLayout layoutAttributesForItemAtIndexPath:indexPath].size; 
} 
+0

我的朋友你有沒有嘗試過使用cmd +我(選擇你所有的代碼:cmd + A,之前這樣做) –

+0

相關知識... thx – Spartanu13

+0

如果有人算出來? Thx – Spartanu13

回答

0

首先,如果你有UIcollectionViewLayout一個子類,爲什麼不設置在故事板

enter image description here

二,你的

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { 

return [collectionViewLayout layoutAttributesForItemAtIndexPath:indexPath].size; 
} 

是多餘的,你有沒有試圖讓一個NSLogreturn[collectionViewLayout layoutAttributesForItemAtIndexPath:indexPath].size;之前它返回一個有效的大小?

+0

是的,它返回一個有效的大小。問題出在主類 – Spartanu13

+0

可能這是問題:[artworkCollectionView reloadData]; artworkCollectionView.collectionViewLayout = layout;但是,如果我在重新加載表格之前放置了佈局,我會得到一個除以0的異常 – Spartanu13

+0

如果您會閱讀我的答案,並嘗試在故事板中設置佈局,但是會出現問題...嘗試執行' ''viewDidLoad'',問題是你在一個並行線程中,一切與UI相關的東西都在主線程上管理 –