Use IOS control Uicollectionview to generate an instance of a drag desktop _ios

Source: Internet
Author: User
Tags set background

The popularity of an app comes from the fact that it provides convenient functionality for the user and, on the other hand, comes from its UI. The UI is an important part of the user experience, and the elements that make up the UI are inseparable from those seemingly independent controls. In the process of development, we should be very familiar with the UITableView! It is true that UITableView has a very powerful function in processing data display, such as Weibo used by Internet red, chat interface of micro-credit social software, etc., this kind of flow layout use UITableView is the most suitable; but after all, UITableView is not omnipotent, When you need to display vertical data, it seems to be stretched, although it's hard not to fall we program apes but why bother to define complex cell? Uicollectionview is specifically used to deal with this kind of layout, the use of Uicollectionview can give us the following advantages: 1. Can be highly customizable content display style 2. Efficient management of large amounts of data.

First of all, let's take a look at this demo's effect chart:

iOS devices do not know if there is now a screen recording of the app, so I can put the action of the action with GIF picture PO come up, if you have a recommendation can tell me ha! About dragging, long press picture after you can drag the picture to the position you want, the other picture will be sorted sequentially, very smooth experience.

After using Uicollectionview, our classes need to implement these protocols: Uicollectionviewdatasource,uicollectionviewdelegateflowlayout,

Uicollectionviewdelegate,uigesturerecognizerdelegate.

Uicollectionviewdatasource: And the Uitableviewdatasource we need to implement in UITableView is a truth that includes the following APIs:

@protocol Uicollectionviewdatasource <NSObject> @required-(Nsinteger) CollectionView: (Uicollectionview *) Coll 
 
Ectionview numberofitemsinsection: (nsinteger) Section; The cell is returned must to retrieved from a call To-dequeuereusablecellwithreuseidentifier:forindexpath:-(UI Collectionviewcell *) CollectionView: (Uicollectionview *) CollectionView Cellforitematindexpath: (NSIndexPath *) 
 
Indexpath; 
 
@optional-(Nsinteger) Numberofsectionsincollectionview: (Uicollectionview *) CollectionView; The view that's returned must be retrieved to call To-dequeuereusablesupplementaryviewofkind:withreuseidentifier: Forindexpath:-(Uicollectionreusableview *) CollectionView: (Uicollectionview *) CollectionView 
 
Viewforsupplementaryelementofkind: (NSString *) kind Atindexpath: (Nsindexpath *) Indexpath; -(BOOL) CollectionView: (Uicollectionview *) CollectionView Canmoveitematindexpath: (Nsindexpath *) IndexPath NS_ 
Available_ios (9_0); -(void) CollectionView: (Uicollectionview *) CollectionView Moveitematindexpath: (Nsindexpath *) Sourceindexpath Toindexpath: (nsindexpath*) 
 
Destinationindexpath Ns_available_ios (9_0); 
 @end

Uicollectionviewdelegateflowlayout:uicollectionviewflowlayout is a class that is designed to manage collectionview layouts. You can adjust the style of our interface by implementing the following functions:

@protocol uicollectionviewdelegateflowlayout <UICollectionViewDelegate> @optional-(cgsize) CollectionView: ( Uicollectionview *) CollectionView layout: (uicollectionviewlayout*) collectionviewlayout Sizeforitematindexpath: ( 
Nsindexpath *) Indexpath; -(Uiedgeinsets) CollectionView: (Uicollectionview *) CollectionView layout: (uicollectionviewlayout*) 
Collectionviewlayout Insetforsectionatindex: (nsinteger) Section; -(CGFloat) CollectionView: (Uicollectionview *) CollectionView layout: (uicollectionviewlayout*) collectionviewlayout 
Minimumlinespacingforsectionatindex: (nsinteger) Section; -(CGFloat) CollectionView: (Uicollectionview *) CollectionView layout: (uicollectionviewlayout*) collectionviewlayout 
Minimuminteritemspacingforsectionatindex: (nsinteger) Section; -(Cgsize) CollectionView: (Uicollectionview *) CollectionView layout: (uicollectionviewlayout*) collectionviewlayout 
Referencesizeforheaderinsection: (nsinteger) Section; -(Cgsize) CollectionView: (Uicollectionview *) CollectionView layout: (uicollectionviewlayout*) collectionviewlayout referencesizeforfooterinsection: (nsinteger) Section; 
 @end

Uicollectionviewdelegate: Like Uitableviewdelegate, here is the agreement inside the function po out, by rewriting the inside function, we can achieve the cell click and drag.

Uigesturerecognizerdelegate: Because we also have a drag function, we need to implement the user gesture protocol.

Well, the basic concept, now let's start to make it happen! The old look directly to look at the source code:

-(void) viewdidload {[Super viewdidload]; 
   
  Do no additional setup after loading the view, typically from a nib. 
  Set background color [Self.view setbackgroundcolor:[uicolor colorwithpatternimage:[uiimage imagenamed:@ "back.jpg"]]]; Set data Source Self.datasource = [[Nsmutablearray alloc] initwithobjects: @ "1.png", @ "2.png", @ "3.png", @ "4.png", @ "5.png", @ "6.png", @ "7.png", @ "8.png", @ "9.png", @ "10.png", @ "11.jpg", @ "12.JPG", @ "13.JPG", @ "14.jpg", @ "15." 
  JPG ", @" 16.png ", @" 17.png ", @" 18.png ", @" 19.png ", @" 20.png ", nil Nil]; 
  Initialize layout self.flow = [[Uicollectionviewflowlayout alloc] init]; 
  Self.collect = [[Uicollectionview alloc] Initwithframe:cgrectzero CollectionViewLayout:self.flow]; 
   
  [Self.collect Setbackgroundcolor:[uicolor Clearcolor]]; Register a cell This step must be implemented [Self.collect Registerclass:[customcollectioncell class] forcellwithreuseidentifier:@ "CustomCell" 
   
  ]; 
  Self.collect.delegate = self; 
   
  Self.collect.dataSource = self; [SELF.COllect SetFrame:self.view.bounds]; 
  Add long press gesture Self.longpressgesturerecognizer = [[Uilongpressgesturerecognizer alloc] init]; 
  [Self.longpressgesturerecognizer addtarget:self Action: @selector (Handlelongpressrecognizer:)]; 
   
  [Self.collect AddGestureRecognizer:self.longPressGestureRecognizer]; 
[Self.view AddSubview:self.collect]; 
 }

In the Viewdidload function, a uicollectionviewflowlayout layout is initialized and needs to be used in conjunction with the Uicollectionview, both of which can be "perfect", like UITableView In the different use of the cell, in the Uicollectionview must first register (registerclass), otherwise it will be in the running process error. How to make the arrangement of the picture can be dragged, where I added a long press gesture for Uicollectionview Uilongpressgesturerecognizer. When we are long on time will trigger Handlelongpressrecognizer, the code is as follows:

-(void) Handlelongpressrecognizer: (Uilongpressgesturerecognizer *) gesture{ 
  switch (gesture.state) { 
    case uigesturerecognizerstatebegan:{ 
      Nsindexpath *path = [Self.collect indexpathforitematpoint:[gesture LocationInView:gesture.view]]; 
      if (path = = nil) {break 
        ; 
      } 
       
      [Self.collect Begininteractivemovementforitematindexpath:path]; 
    } 
      break; 
    Case uigesturerecognizerstatechanged: 
      [Self.collect updateinteractivemovementtargetposition:[gesture LocationInView:gesture.view]]; 
      break; 
    Case uigesturerecognizerstateended: 
      [Self.collect endinteractivemovement]; 
      break; 
    Default: 
      [Self.collect cancelinteractivemovement]; 
      break; 
  } 
} 

Good-looking interface to seize the user's heart, here I have customized the cell inherits from the Uicollectionviewcell,cell display in the picture will scale according to the size of its own picture, so that our desktop will look like a horizontal version of the picture and the vertical version of the picture, If you do not customize the words are square nine Sudoku, or spend some time to customize the display effect bar! Customcollectioncell's code is as follows:

#import "CustomCollectionCell.h" @implementation customcollectioncell @synthesize Imagev = _imagev; 
@synthesize Labelv = _labelv; 
 
@synthesize Boundview = _boundview; 
  -(ID) initWithFrame: (cgrect) frame{self = [super Initwithframe:frame]; 
    Init attributes if (self) {[self setbackgroundcolor:[uicolor clearcolor]]; 
    Self.imagev = [[Uiimageview alloc] Initwithframe:cgrectzero]; 
    Self.labelv = [[Uilabel alloc] Initwithframe:cgrectzero]; 
    Self.boundview = [[UIView alloc] Initwithframe:cgrectzero]; 
    [Self.boundview Setbackgroundcolor:[uicolor Whitecolor]]; 
    [Self.boundview AddSubview:self.imageV]; 
    [Self addSubview:self.boundView]; 
  [Self AddSubview:self.labelV]; 
return self; 
  }-(void) Setimagewithtext: (UIImage *) image text: (NSString *) text{if (!image) {return; 
  } cgfloat imgwidth = Image.size.width; 
  CGFloat imgheight = image.size.height; 
  CGFloat iconwidth = 0.0; 
   
  CGFloat iconheight = 0.0; if (iMgwidth > ImgHeight) {iconheight = Roundf (((self.frame.size.width-16) *imgheight)/imgwidth); 
    Iconwidth = self.frame.size.width-16; 
    [Self.boundview setframe:cgrectmake (0, self.frame.size.height-iconheight-16, Iconwidth +, IconHeight + 16)]; 
  [Self.imagev Setframe:cgrectmake (8, 8, Iconwidth, Iconheight)]; 
    }else{iconwidth = Roundf (((self.frame.size.width-16) *imgwidth)/imgheight); 
    Iconheight = self.frame.size.height-16; 
    [Self.boundview Setframe:cgrectmake (ROUNDF (self.frame.size.width-iconwidth)/2), 0, Iconwidth +, IconHeight + 16)]; 
  [Self.imagev Setframe:cgrectmake (8, 8, Iconwidth, Iconheight)]; 
} [Self.imagev Setimage:image];  } @end

These are the main components of the demo, Uicollectionview there are a lot of elements in this is not mentioned, I will later study this control more advanced use, this article is like an appetizer before the meal, I hope you like. Attach the source code for this example:

@implementation viewcontroller @synthesize dataSource = _datasource; 
@synthesize Longpressgesturerecognizer = _longpressgesturerecognizer; 
@synthesize flow = _flow; 
 
@synthesize collect = _collect; 
  -(void) viewdidload {[Super viewdidload]; 
   
  Do no additional setup after loading the view, typically from a nib. 
  Set background color [Self.view setbackgroundcolor:[uicolor colorwithpatternimage:[uiimage imagenamed:@ "back.jpg"]]]; Set data Source Self.datasource = [[Nsmutablearray alloc] initwithobjects: @ "1.png", @ "2.png", @ "3.png", @ "4.png", @ "5.png", @ "6.png", @ "7.png", @ "8.png", @ "9.png", @ "10.png", @ "11.jpg", @ "12.JPG", @ "13.JPG", @ "14.jpg", @ "15." 
  JPG ", @" 16.png ", @" 17.png ", @" 18.png ", @" 19.png ", @" 20.png ", nil Nil]; 
  Initialize layout self.flow = [[Uicollectionviewflowlayout alloc] init]; 
  Self.collect = [[Uicollectionview alloc] Initwithframe:cgrectzero CollectionViewLayout:self.flow]; 
   
  [Self.collect Setbackgroundcolor:[uicolor Clearcolor]]; NoteRegister cell This step must realize [Self.collect Registerclass:[customcollectioncell class] forcellwithreuseidentifier:@ "CustomCell"]; 
  Self.collect.delegate = self; 
   
  Self.collect.dataSource = self; 
   
  [Self.collect SetFrame:self.view.bounds]; 
  Add long press gesture Self.longpressgesturerecognizer = [[Uilongpressgesturerecognizer alloc] init]; 
  [Self.longpressgesturerecognizer addtarget:self Action: @selector (Handlelongpressrecognizer:)]; 
   
  [Self.collect AddGestureRecognizer:self.longPressGestureRecognizer]; 
[Self.view AddSubview:self.collect]; 
  }-(void) didreceivememorywarning {[Super didreceivememorywarning]; 
Dispose of any of the can is recreated. }-(void) Handlelongpressrecognizer: (Uilongpressgesturerecognizer *) gesture{switch (gesture.state) {case Uige sturerecognizerstatebegan:{Nsindexpath *path = [Self.collect indexpathforitematpoint:[gesture locationInView:gestu 
      Re.view]]; 
      if (path = = nil) {break; 
       
     } [Self.collect Begininteractivemovementforitematindexpath:path]; 
    } break; Case uigesturerecognizerstatechanged: [Self.collect updateinteractivemovementtargetposition:[gesture LocationInVie 
      W:gesture.view]]; 
    Break 
      Case uigesturerecognizerstateended: [Self.collect endinteractivemovement]; 
    Break 
      Default: [Self.collect cancelinteractivemovement]; 
  Break #pragma mark Uicollectionviewdatasource-(Nsinteger) CollectionView: (Uicollectionview *) CollectionView numberOfIt 
Emsinsection: (Nsinteger) section{return self.dataSource.count; 
}-(Nsinteger) Numberofsectionsincollectionview: (Uicollectionview *) collectionview{return 1; }-(Uicollectionviewcell *) CollectionView: (Uicollectionview *) CollectionView Cellforitematindexpath: (NSIndexPath *) indexpath{Customcollectioncell * cell = (Customcollectioncell *) [CollectionView 
  dequeuereusablecellwithreuseidentifier:@ "Customcell" Forindexpath:indexpath]; UIimage *image = [UIImage imagenamed:[self.datasource ObjectAtIndex:indexPath.row]]; 
   
  [Cell Setimagewithtext:image text:@ "]; 
return cell; }-(BOOL) CollectionView: (Uicollectionview *) CollectionView Canmoveitematindexpath: (Nsindexpath *) indexPath{return 
YES; }-(void) CollectionView: (Uicollectionview *) CollectionView Moveitematindexpath: (Nsindexpath *) Sourceindexpath 
  Toindexpath: (nsindexpath*) destinationindexpath{id item = [self.datasource ObjectAtIndex:sourceIndexPath.item]; 
   
  [Self.datasource Removeobject:item]; 
[Self.datasource Insertobject:item AtIndex:destinationIndexPath.item]; #pragma mark Uicollectionviewdelegate-(void) CollectionView: (Uicollectionview *) CollectionView Didselectitematinde XPath: (Nsindexpath *) indexpath{Testviewcontroller *test = [[Testviewcontroller alloc] initwithnibname:@ " 
  Testviewcontroller "Bundle:nil]; 
  NSString *imagename = [Self.datasource objectAtIndex:indexPath.row]; 
   
  Test.imagename = imagename;[Self.navigationcontroller pushviewcontroller:test Animated:yes]; }-(BOOL) CollectionView: (Uicollectionview *) CollectionView Shouldhighlightitematindexpath: (Nsindexpath *) IndexPath 
{return YES; //Check magnification effect-(void) CollectionView: (Uicollectionview *) CollectionView Didhighlightitematindexpath: (Nsindexpath *) 
indexpath{//Customcollectioncell * cell = (Customcollectioncell *) [CollectionView Cellforitematindexpath:indexpath]; 
[UIView animatewithduration:1 animations:^{//Cell.transform = Cgaffinetransformmakescale (2.0f, 2.0f); 
//  }]; }//Narrowing effect-(void) CollectionView: (Uicollectionview *) CollectionView Didunhighlightitematindexpath: (Nsindexpath *) 
indexpath{//Customcollectioncell * cell = (Customcollectioncell *) [CollectionView Cellforitematindexpath:indexpath]; 
[UIView animatewithduration:1 animations:^{//Cell.transform = Cgaffinetransformmakescale (1.0f, 1.0f); 
//  }]; #pragma mark Uicollectionviewdelegateflowlayout-(cgsize) CollectionView: (Uicollectionview *) CollectionView layout: (uicollectionviewlayout*) collectionviewlayout 
Sizeforitematindexpath: (Nsindexpath *) indexpath{return Cgsizemake (100, 100); }/* * upper Left/Right spacing * * (uiedgeinsets) CollectionView: (Uicollectionview *) CollectionView layout: (uicollectionviewlayout* 
) collectionviewlayout Insetforsectionatindex: (nsinteger) section{return Uiedgeinsetsmake (15, 15, 15, 15); }/* * Item Space/*-(CGFloat) CollectionView: (Uicollectionview *) CollectionView layout: (uicollectionviewlayout*) 
Collectionviewlayout Minimuminteritemspacingforsectionatindex: (Nsinteger) section{return 8; * * * * leading-(CGFloat) CollectionView: (Uicollectionview *) CollectionView layout: (uicollectionviewlayout*) Colle 
Ctionviewlayout Minimumlinespacingforsectionatindex: (nsinteger) section{return 10; 
 }

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.