iOS Imitation Android gallery controls

Source: Internet
Author: User

No controls similar to Android Gallery have been found on iOS because they need to be used on the project. Implemented with Uicollectionview



Viewcontroller.m

#import "ViewController.h" #import "ImageCell.h" #import "LineLayout.h" @interface Viewcontroller () < Uicollectionviewdatasource, uicollectionviewdelegate> @property (nonatomic, strong) Nsmutablearray *images;@ Property (nonatomic, weak) Uicollectionview *collectionview; @end @implementation viewcontrollerstatic NSString *const                ID = @ "image";-(Nsmutablearray *) images{if (!_images) {self.images = [[Nsmutablearray alloc] init];        for (int i = 1; i<=20; i++) {[Self.images addobject:[nsstring stringwithformat:@ '%d ', I]]; }} return _images;}        -(void) viewdidload {[Super viewdidload];    CGFloat w = self.view.frame.size.width;    CGRect rect = CGRectMake (0, +, W, 200); Uicollectionview *collectionview = [[Uicollectionview alloc] Initwithframe:rect collectionviewlayout:[[linelayout    ALLOC] [init]];    Collectionview.datasource = self;    Collectionview.delegate = self; [CollectionView registernib:[uinib nibwithnibname:@ "imagecell "Bundle:nil] forcellwithreuseidentifier:id];    [Self.view Addsubview:collectionview];    Self.collectionview = CollectionView; Collectionviewlayout://Uicollectionviewlayout//uicollectionviewflowlayout}-(void) Touchesbegan: (NSSet *) Touc        Hes withevent: (uievent *) event{if ([Self.collectionView.collectionViewLayout Iskindofclass:[linelayout class]]) {    [Self.collectionview Setcollectionviewlayout:[[uicollectionviewflowlayout alloc] init] animated:yes];    } else {[Self.collectionview setcollectionviewlayout:[[linelayout alloc] init] animated:yes]; }} #pragma mark-<uicollectionviewdatasource>-(Nsinteger) CollectionView: (Uicollectionview *) CollectionView Numberofitemsinsection: (Nsinteger) section{return self.images.count;} -(Uicollectionviewcell *) CollectionView: (Uicollectionview *) CollectionView Cellforitematindexpath: (NSIndexPath *) indexpath{Imagecell *cell = [CollectionView dequeuereusablecellwithreuseidentifier:id ForIndexPath:indexPATH];    Cell.image = Self.images[indexpath.item]; return cell;} -(void) CollectionView: (Uicollectionview *) CollectionView Didselectitematindexpath: (Nsindexpath *) indexPath{//        Delete model data [self.images RemoveObjectAtIndex:indexPath.item]; Delete ui (Refresh UI) [CollectionView Deleteitemsatindexpaths:@[indexpath];} @end

Linelayout.m

#import "LineLayout.h" static const cgfloat ITEMWH =, @implementation linelayout-(instancetype) init{if (self = [sup ER init]) {} return self;} /** * re-layout as long as the displayed boundary changes: Internally the Preparelayout and Layoutattributesforelementsinrect methods are called back to get the layout properties of all cells */-(BOOL) Shouldinvalidatelayoutforboundschange: (cgrect) newbounds{return YES;}              /** * Used to set CollectionView stop scrolling at that moment of position * * @param proposedcontentoffset originally CollectionView stop scrolling at that moment of position * @param velocity Scrolling speed */-(cgpoint) Targetcontentoffsetforproposedcontentoffset: (cgpoint) Proposedcontentoffset    Withscrollingvelocity: (cgpoint) velocity{//1. Calculate the range of ScrollView last stop CGRect lastrect;    Lastrect.origin = Proposedcontentoffset;        Lastrect.size = self.collectionView.frame.size;        Calculate the center of the screen x cgfloat CenterX = proposedcontentoffset.x + self.collectionView.frame.size.width * 0.5;        2. Remove all properties within this range nsarray *array = [self layoutattributesforelementsinrect:lastrect]; 3. Traverse All properties CGFloat adjustoffsetx = MaxfloaT  For (uicollectionviewlayoutattributes *attrs in array) {if (ABS (Attrs.center.x-centerx) < ABS (ADJUSTOFFSETX))        {adjustoffsetx = Attrs.center.x-centerx; }} return Cgpointmake (Proposedcontentoffset.x + adjustoffsetx, proposedcontentoffset.y);}         /** * Some of the initialization work is best implemented here */-(void) preparelayout{[Super Preparelayout];    The size of each cell self.itemsize = Cgsizemake (Itemwh, ITEMWH);    CGFloat inset = (SELF.COLLECTIONVIEW.FRAME.SIZE.WIDTH-HMITEMWH) * 0.5;    Self.sectioninset = Uiedgeinsetsmake (0, inset, 0, inset);    Set Horizontal scrolling self.scrolldirection = uicollectionviewscrolldirectionhorizontal;        self.minimumlinespacing = Itemwh * 0.7; Each cell (item) has its own uicollectionviewlayoutattributes//each indexpath has its own uicollectionviewlayoutattributes}/** Effective Distance: When the middle X of item is within hmactivedistance of the middle X of the screen, it will only start to zoom in, and all other cases are reduced */static cgfloat const Activedistance = 150;/** Scaling factor: The higher the value, Item will be larger */static cgfloat const Scalefactor = 0.6;-(Nsarray *) LayoUtattributesforelementsinrect: (CGRect) rect{//0. Calculate the visible rectangle box CGRect visiablerect;    Visiablerect.size = self.collectionView.frame.size;        Visiablerect.origin = Self.collectionView.contentOffset;    1. Obtain the default cell's uicollectionviewlayoutattributes nsarray *array = [Super Layoutattributesforelementsinrect:rect];        Calculate the center of the screen x cgfloat CenterX = self.collectionview.contentoffset.x + self.collectionView.frame.size.width * 0.5; 2. Traverse all layout properties for (uicollectionviewlayoutattributes *attrs in array) {//If not on the screen, skip directly if (!                Cgrectintersectsrect (Visiablerect, attrs.frame)) continue;                The midpoint of each item x cgfloat Itemcenterx = attrs.center.x; The smaller the gap, the larger the scaling ratio cgfloat scale = 1 + scalefactor * (1-(ABS (Itemcenterx-centerx)/Ac) based on the distance to the center of the screen        Tivedistance));    Attrs.transform = Cgaffinetransformmakescale (scale, scale); } return array; @end

imagecell.m

#import "ImageCell.h" @interface Imagecell () @property (weak, nonatomic) Iboutlet Uiimageview *imageview;@ End@implementation imagecell-(void) awakefromnib {    self.imageView.layer.borderWidth = 3;    Self.imageView.layer.borderColor = [Uicolor Whitecolor]. Cgcolor;    Self.imageView.layer.cornerRadius = 3;    Self.imageView.clipsToBounds = YES;} -(void) SetImage: (NSString *) image{    _image = [image copy];        Self.imageView.image = [UIImage imagenamed:image];} @end


iOS Imitation Android gallery controls

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.