我正在使用UICollectionView,我有一个主类,另一个是UICollectionViewFlowLayout的子类。事情就是主要类中单元格的宽度和高度为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 :(得分:0)
首先,如果你有一个UIcollectionViewLayout
的子类,为什么不在故事板中设置
第二,你的
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return [collectionViewLayout layoutAttributesForItemAtIndexPath:indexPath].size;
}
是多余的,您是否尝试在NSLog
上return
之前[collectionViewLayout layoutAttributesForItemAtIndexPath:indexPath].size;
返回有效大小?