Click implementation of the button in the cell of iOS advanced development--collectionview

Source: Internet
Author: User

When I first started learning iOS, I asked the big gods what was the hardest part of iOS development. Some people say that custom controls, UI, and interaction design. At that time I was doubtful, with the development of their own in-depth, I really have experience. Development of an app product, a large part of the time is to deal with the UI. Because many of the features in the development are directly encapsulated or have ready-made templates to use, only the UI is changeable according to the different apps. So today we continue to study the more advanced control--uicollectionview in iOS to implement the Click action of the button in the cell. The demo I have submitted to: Https://github.com/chenyufeng1991/CollectionView. It contains a lot of CollectionView function realization, welcome everyone to download. For the dynamic addition of section and cell parts, you can refer to: "iOS project development Combat-to achieve the dynamic increase of uicollectionview cells and sections."

In this demand, we need to add a button to a cell, and then implement the button click Effect. As with clicking Cell, we need to get the section and cell value of the button when we click the button. That's indexpath.section and indexpath.row. I'll be in https://github.com/chenyufeng1991/CollectionView/tree/master/%E5%8A%A8%. E6%80%81%e5%a2%9e%e5%8a%a0cell%e5%92%8csection%e5%ae%9e%e7%8e%b0. On the basis of continued development.

(1) Custom cell

I've included a button and a text in the cell. The custom code is as follows:

CollectionViewCell.h:

#import <UIKit/UIKit.h> @interface collectionviewcell:uicollectionviewcell//Every cell is a uiview, A cell contains a picture and text;//@property (Nonatomic,strong) UIView *cellview; @property (strong,nonatomic) UIButton * ImageButton, @property (strong,nonatomic) UILabel *desclabel; @end


COLLECTIONVIEWCELL.M:

#import "CollectionViewCell.h" #define SCREEN_WIDTH ([[[UIScreen Mainscreen] bounds].size.width) #define Screen_height ( [[UIScreen Mainscreen] bounds].size.height) @implementation collectionviewcell-(instancetype) initWithFrame: (CGRect ) frame{Self  = [Super Initwithframe:frame];  The IF (self) {      //here needs to initialize ImageView;    Self.imagebutton = [[UIButton alloc] Initwithframe:cgrectmake (( SELF.BOUNDS.SIZE.WIDTH-32)/2, (SELF.BOUNDS.SIZE.WIDTH-32)/2, +, +)];    Self.imageButton.tag = +;            Self.desclabel = [[UILabel alloc] Initwithframe:cgrectmake ((self.bounds.size.width-100)/2, (Self.bounds.size.width- )/2 +, (+)];    Self.descLabel.textAlignment = Nstextalignmentcenter;    Self.desclabel.font=[uifont Systemfontofsize:10];    Self.descLabel.tag = 101;        [Self.contentview AddSubview:self.imageButton];    [Self.contentview AddSubview:self.descLabel];          }  return self;} @end


(2) In order to click this button, we have to find the button according to each cell, so we need to

-(Uicollectionviewcell *) CollectionView: ( Uicollectionview *) CollectionView Cellforitematindexpath: (nsindexpath *) The indexpath{} method is implemented as follows:

-(Uicollectionviewcell *) CollectionView: (Uicollectionview *) CollectionView Cellforitematindexpath: (NSIndexPath *) indexpath{Collectionviewcell *cell = [CollectionView dequeuereusablecellwithreuseidentifier:@ "CollectionCell"  Forindexpath:indexpath]; Cell.imageView.image = [UIImage imagenamed:[[self.dataarray objectAtIndex:indexPath.section] Objectatindex:      Indexpath.row]];  Set the Device Picture button's Click event;//UIButton *deviceimagebutton = (uibutton*) [cell viewwithtag:100]; [Deviceimagebutton addtarget:self Action: @selector (Devicebuttonpressed:row:) forControlEvents:    UIControlEventTouchUpInside];  Find each button; UIButton *deviceimagebutton = Cell.imagebutton; [Deviceimagebutton addtarget:self Action: @selector (devicebuttonpressed:) forControlEvents:    UIControlEventTouchUpInside]; Add a border to each cell; cell.layer.borderColor = [Uicolor Graycolor].  Cgcolor;        Cell.layer.borderWidth = 0.3;  [Cell.imagebutton setbackgroundimage:[uiimage imagenamed:@ "0"] forstate:uicontrolstatenormal]; Cell.dEsclabel.text = @ "text";  return cell; }

(3) Click to implement the button. Here is the point, if we want to operate directly on the button, it is impossible to complete. You must pay attention to the hierarchical relationship between the button and the cell. If you use storyboard or nib, you can open the view hierarchy, because my cell here is code generation, it is not intuitive for everyone to see.   But their hierarchical relationship is: Cell-->contentview-->button. So note that we have to find the cell that corresponds to the button in order to fully determine the section and row of the button. So pay attention to two of the code: the Superview method. The implementation code for this button is as follows:

-(void) devicebuttonpressed: (ID) sender{    UIView *v = [Sender superview];//Get parent Class View  Collectionviewcell *cell = ( Collectionviewcell *) [v superview];//get cell    nsindexpath *indexpath = [Self.collectionview Indexpathforcell:cell] ;//Get the cell corresponding Indexpath;    NSLog (@ "Device Picture button was clicked:%ld        %ld", (Long) indexpath.section, (long) indexpath.row);  }


(4) Run the program, we can find the click button to get a response, and print out the button's indexpath.section and Indexpath.row. Click the button and click on the cell is independent of each other, there is no impact, you can respond to the event processing separately.


Summary: Through the actual development we can find, TableView and CollectionView is too similar, both after all inherit from Scrollview,collectionview is actually tableview expansion. Now often is to look at tableview some of the effects or code, and then try to collectionview on the implementation, vice versa. It's like watching OC write swift or watch Swift write OC. If you are familiar with Android, you will find that today we are talking about the TableView, CollectionView relationship is like the ListView and Recycleview in Android's relationship. Only through mastery can we achieve the results we want. Let's study together and make progress together.



Recently open source IOS app, high-profile Evernote https://github.com/chenyufeng1991/iOS-Oncenote. Welcome everyone to praise and follow the project progress. You can also install it on your phone and try it on.

GitHub home: https://github.com/chenyufeng1991. Welcome everyone to visit!


Click implementation of a button in the cell of the iOS advanced development--collectionview

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.