Skip to content

Instantly share code, notes, and snippets.

@puttin
Created Apr 9, 2013
Embed
What would you like to do?
An advanced example about the UICollectionView and custom layout NEED QuartzCore.framework
/*
File: LineLayout.h
Abstract: Simple flow layout to lay out items in a line.
Version: 1.0
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2012 Apple Inc. All Rights Reserved.
WWDC 2012 License
NOTE: This Apple Software was supplied by Apple as part of a WWDC 2012
Session. Please refer to the applicable WWDC 2012 Session for further
information.
IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a non-exclusive license, under
Apple's copyrights in this original Apple software (the "Apple
Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#import <UIKit/UIKit.h>
@interface LineLayout : UICollectionViewFlowLayout
@end
/*
File: LineLayout.m
Abstract: Simple flow layout to lay out items in a line.
Version: 1.0
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2012 Apple Inc. All Rights Reserved.
WWDC 2012 License
NOTE: This Apple Software was supplied by Apple as part of a WWDC 2012
Session. Please refer to the applicable WWDC 2012 Session for further
information.
IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a non-exclusive license, under
Apple's copyrights in this original Apple software (the "Apple
Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#import "LineLayout.h"
#define ITEM_SIZE 200.0
@implementation LineLayout
#define ACTIVE_DISTANCE 200
#define ZOOM_FACTOR 0.3
-(id)init
{
self = [super init];
if (self) {
self.itemSize = CGSizeMake(ITEM_SIZE, ITEM_SIZE);
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
self.sectionInset = UIEdgeInsetsMake(50, 0.0, 50, 0.0);
self.minimumInteritemSpacing = 500.0;
self.minimumLineSpacing = 50.0;
}
return self;
}
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)oldBounds
{
return YES;
}
-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray* array = [super layoutAttributesForElementsInRect:rect];
CGRect visibleRect;
visibleRect.origin = self.collectionView.contentOffset;
visibleRect.size = self.collectionView.bounds.size;
for (UICollectionViewLayoutAttributes* attributes in array) {
if (CGRectIntersectsRect(attributes.frame, rect)) {
CGFloat distance = CGRectGetMidX(visibleRect) - attributes.center.x;
CGFloat normalizedDistance = distance / ACTIVE_DISTANCE;
if (ABS(distance) < ACTIVE_DISTANCE) {
CGFloat zoom = 1 + ZOOM_FACTOR*(1 - ABS(normalizedDistance));
attributes.transform3D = CATransform3DMakeScale(zoom, zoom, 1.0);
attributes.zIndex = 1;
}
}
}
return array;
}
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
CGFloat offsetAdjustment = MAXFLOAT;
CGFloat horizontalCenter = proposedContentOffset.x + (CGRectGetWidth(self.collectionView.bounds) / 2.0);
CGRect targetRect = CGRectMake(proposedContentOffset.x, 0.0, self.collectionView.bounds.size.width, self.collectionView.bounds.size.height);
NSArray* array = [super layoutAttributesForElementsInRect:targetRect];
for (UICollectionViewLayoutAttributes* layoutAttributes in array) {
CGFloat itemHorizontalCenter = layoutAttributes.center.x;
if (ABS(itemHorizontalCenter - horizontalCenter) < ABS(offsetAdjustment)) {
offsetAdjustment = itemHorizontalCenter - horizontalCenter;
}
}
return CGPointMake(proposedContentOffset.x + offsetAdjustment, proposedContentOffset.y);
}
@end
//
// main.m
// AdvancedUICollectionViewLayout
//
// Created by Puttin Wong on 4/8/13.
// Copyright (c) 2013 Puttin Wong. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import "LineLayout.h"
#pragma mark -
#pragma mark DemoCollectionViewCell
@interface DemoCollectionViewCell : UICollectionViewCell
-(void)setImage:(UIImage *)image;
@property (strong, nonatomic) UILabel* label;
@property (nonatomic, strong) UIImageView *imageView;
@end
@implementation DemoCollectionViewCell
- (id)initWithFrame:(CGRect)frame
{
if (!(self = [super initWithFrame:frame])) return nil;
self.imageView = [[UIImageView alloc] initWithFrame:CGRectInset(CGRectMake(0, 0, CGRectGetWidth(frame), CGRectGetHeight(frame)), 2, 2)];
self.imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[self.contentView addSubview:self.imageView];
self.label = [[UILabel alloc] initWithFrame:CGRectInset(CGRectMake(0, 0, CGRectGetWidth(frame), CGRectGetHeight(frame)), 5, 5)];
self.label.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
self.label.textAlignment = NSTextAlignmentCenter;
self.label.font = [UIFont boldSystemFontOfSize:40.0];
self.label.backgroundColor = [UIColor clearColor];
self.label.textColor = [UIColor blackColor];
[self.contentView addSubview:self.label];;
// make sure we rasterize nicely for retina
self.layer.rasterizationScale = [UIScreen mainScreen].scale;
self.layer.shouldRasterize = YES;
self.backgroundColor = [UIColor whiteColor];
return self;
}
-(void)prepareForReuse
{
[self setImage:nil];
}
-(void)setImage:(UIImage *)image
{
self.imageView.image = image;
}
-(void)setText:(NSString *)str
{
self.label.text = str;
}
@end
#pragma mark -
#pragma mark StackedPhotoLayout
static NSUInteger const RotationCount = 32;
static NSUInteger const RotationStride = 3;
static NSUInteger const PhotoCellBaseZIndex = 100;
static NSString * const PhotoCellKind = @"PhotoCell";
static float imageItemSize = 90.0f;
@interface StackedPhotoLayout : UICollectionViewLayout
@property (nonatomic) UIEdgeInsets sectionInset;
@property (nonatomic) CGSize itemSize;
@property (nonatomic) CGFloat minimumInterItemSpacing;
@property (nonatomic) CGFloat minimumLineSpacing;
@property (nonatomic, strong) NSDictionary *layoutInfo;
@property (nonatomic, strong) NSArray *rotations;
@end
@implementation StackedPhotoLayout{
NSUInteger maxColumnNum;
CGFloat realInterItemSpacing;
}
- (id)init
{
self = [super init];
if (self) {
[self setup];
}
return self;
}
- (void)setup
{
self.itemSize = CGSizeMake(imageItemSize, imageItemSize);
self.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
self.minimumInterItemSpacing = 15;
self.minimumLineSpacing = 15;
// create rotations at load so that they are consistent during prepareLayout
NSMutableArray *rotations = [NSMutableArray arrayWithCapacity:RotationCount];
CGFloat percentage = 0.0f;
for (NSInteger i = 0; i < RotationCount; i++) {
// ensure that each angle is different enough to be seen
CGFloat newPercentage = 0.0f;
do {
newPercentage = ((CGFloat)(arc4random() % 220) - 110) * 0.0001f;
} while (fabsf(percentage - newPercentage) < 0.006);
percentage = newPercentage;
CGFloat angle = 2 * M_PI * (1.0f + percentage);
CATransform3D transform = CATransform3DMakeRotation(angle, 0.0f, 0.0f, 1.0f);
[rotations addObject:[NSValue valueWithCATransform3D:transform]];
}
self.rotations = rotations;
}
- (void)prepareLayout
{
maxColumnNum = [self maxColumn];
realInterItemSpacing = [self realInterItemSpacing];
// NSLog(@"%u %f",maxColumnNum,realInterItemSpacing);
NSMutableDictionary *newLayoutInfo = [NSMutableDictionary dictionary];
NSMutableDictionary *cellLayoutInfo = [NSMutableDictionary dictionary];
NSInteger sectionCount = [self.collectionView numberOfSections];
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
for (NSInteger section = 0; section < sectionCount; section++) {
NSInteger itemCount = [self.collectionView numberOfItemsInSection:section];
for (NSInteger item = 0; item < itemCount; item++) {
indexPath = [NSIndexPath indexPathForItem:item inSection:section];
UICollectionViewLayoutAttributes *itemAttributes =
[UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
itemAttributes.frame = [self frameForAlbumPhotoAtIndexPath:indexPath];
itemAttributes.transform3D = [self transformForAlbumPhotoAtIndex:indexPath];
itemAttributes.zIndex = PhotoCellBaseZIndex + itemCount - item;
cellLayoutInfo[indexPath] = itemAttributes;
}
}
newLayoutInfo[PhotoCellKind] = cellLayoutInfo;
self.layoutInfo = newLayoutInfo;
}
-(CGSize)collectionViewContentSize
{
NSUInteger rowCount = [self.collectionView numberOfSections]/maxColumnNum;
if ([self.collectionView numberOfSections] % maxColumnNum) rowCount++;
CGFloat height = self.sectionInset.top + rowCount * self.itemSize.height + (rowCount - 1) * self.minimumLineSpacing + self.sectionInset.bottom;
return CGSizeMake([self collectionView].frame.size.width, height);
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
return self.layoutInfo[PhotoCellKind][indexPath];
}
-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect
{
NSMutableArray *allAttributes = [NSMutableArray arrayWithCapacity:self.layoutInfo.count];
[self.layoutInfo enumerateKeysAndObjectsUsingBlock:^(NSString *elementIdentifier, NSDictionary *elementsInfo, BOOL *stop) {
[elementsInfo enumerateKeysAndObjectsUsingBlock:^(NSIndexPath *indexPath, UICollectionViewLayoutAttributes *attributes, BOOL *innerStop) {
if (CGRectIntersectsRect(rect, attributes.frame)) {
[allAttributes addObject:attributes];
}
}];
}];
return allAttributes;
}
- (NSUInteger)maxColumn {
NSUInteger i = 0;
BOOL done = NO;
while (done == NO) {
NSInteger leftSpace = [self collectionView].frame.size.width - self.sectionInset.left - self.sectionInset.right - i * self.itemSize.width - i * self.minimumInterItemSpacing ;
if (leftSpace < self.itemSize.width) {
done = YES;
} else {
i++;
}
}
if (i==0) {
NSLog(@"ERROR: CANNOT put even one item in a row");
}
return i;
}
- (CGFloat)realInterItemSpacing {
if (maxColumnNum == 1) {
return self.minimumInterItemSpacing;
}
return ([self collectionView].frame.size.width - self.sectionInset.left - self.sectionInset.right - maxColumnNum * self.itemSize.width) / (maxColumnNum - 1);
}
- (NSIndexPath *)rowAndColumnForSection:(NSUInteger)section {
NSUInteger row = section/maxColumnNum;
NSUInteger column = section % maxColumnNum;
return [NSIndexPath indexPathForRow:column inSection:row];
}
- (CGRect)frameForAlbumPhotoAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger section = indexPath.section;
NSIndexPath *rc = [self rowAndColumnForSection:section];
CGFloat originX = self.sectionInset.left + (self.itemSize.width + realInterItemSpacing)* rc.row;
CGFloat originY = self.sectionInset.top + (self.itemSize.height + self.minimumLineSpacing)* rc.section;
return CGRectMake(originX, originY, self.itemSize.width, self.itemSize.width);
}
- (CATransform3D)transformForAlbumPhotoAtIndex:(NSIndexPath *)indexPath
{
NSInteger offset = (indexPath.section * RotationStride + indexPath.item);
return [self.rotations[offset % RotationCount] CATransform3DValue];
}
@end
#pragma mark -
#pragma mark DemoCollectionViewController
static NSString *ItemIdentifier = @"ItemIdentifier";
static float imageSize = 90.0f;
@interface DemoCollectionViewController : UICollectionViewController
@property (nonatomic, strong) NSMutableArray *albums;
@property (nonatomic, strong) NSMutableArray *realAlbums;
@end
@implementation DemoCollectionViewController
-(void)loadView
{
StackedPhotoLayout *stackedLayout = [[StackedPhotoLayout alloc] init];
self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:stackedLayout];
[self.collectionView registerClass:[DemoCollectionViewCell class] forCellWithReuseIdentifier:ItemIdentifier];
self.collectionView.delegate = self;
self.collectionView.dataSource = self;
self.collectionView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reset)];
self.albums = [NSMutableArray array];
NSUInteger randMax = 10;
NSUInteger loopCount = (NSUInteger)(arc4random()%randMax+15);
for (NSUInteger i =0; i<loopCount; i++) {
NSMutableArray *arr=[[NSMutableArray alloc] init];
NSUInteger loopCount1 = (NSUInteger)(arc4random()%randMax+5);
for (NSUInteger j =0; j<loopCount1; j++) {
[arr addObject:[DemoCollectionViewController imageWithRandomColorInSize:CGSizeMake(imageSize, imageSize)]];
}
[self.albums addObject:arr];
}
self.realAlbums = [self.albums mutableCopy];
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
[super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
// [self.collectionView reloadData];
[self.collectionView.collectionViewLayout invalidateLayout];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Get A Image
+(UIColor *)randomColor
{
static BOOL seeded = NO;
if (!seeded) {seeded = YES; srandom(time(NULL));}
CGFloat red = (CGFloat)random()/(CGFloat)RAND_MAX;
CGFloat blue = (CGFloat)random()/(CGFloat)RAND_MAX;
CGFloat green = (CGFloat)random()/(CGFloat)RAND_MAX;
return [UIColor colorWithRed:red green:green blue:blue alpha:1.0f];
}
+ (UIImage *)imageWithRandomColorInSize:(CGSize)size {
return [self imageWithColor:[self randomColor] andSize:size];
}
+ (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size {
CGRect rect = CGRectMake(0.0f, 0.0f, size.height, size.width);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
#pragma mark - UICollectionView DataSource & Delegate methods
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return self.realAlbums.count;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [self.realAlbums[section] count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
DemoCollectionViewCell *cell = (DemoCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:ItemIdentifier forIndexPath:indexPath];
[cell setImage:[self.realAlbums[indexPath.section] objectAtIndex:indexPath.row]];
[cell setText:[NSString stringWithFormat:@"%u,%u",indexPath.section,indexPath.row]];
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSMutableIndexSet *set = [[NSMutableIndexSet alloc] init];
for (NSUInteger i =0; i<[self numberOfSectionsInCollectionView:collectionView]; i++) {
if (i != indexPath.section) {
[set addIndex:i];
}
}
[self.realAlbums removeObjectsAtIndexes:set];
[collectionView deleteSections:set];
collectionView.collectionViewLayout = [[LineLayout alloc] init];
[collectionView reloadData];
// [self performSelector:@selector(reset) withObject:nil afterDelay:2];
}
- (void)reset {
self.realAlbums = [self.albums mutableCopy];
[self.collectionView reloadData];
self.collectionView.collectionViewLayout = [[StackedPhotoLayout alloc] init];
}
@end
#pragma mark -
#pragma mark Application Setup
@interface DemoAppDelegate : NSObject <UIApplicationDelegate>
{
UIWindow *window;
}
@end
@implementation DemoAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[application setStatusBarHidden:YES];
window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
DemoCollectionViewController *vc = [[DemoCollectionViewController alloc] init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
window.rootViewController = nav;
[window makeKeyAndVisible];
return YES;
}
@end
#pragma mark -
#pragma mark main
int main(int argc, char *argv[]) {
@autoreleasepool {
int retVal = UIApplicationMain(argc, argv, nil, @"DemoAppDelegate");
return retVal;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment