Final:
Sub-MVC three-layer design; There are two types of custom cells, one is Maincell, the data source is provided by Modelarr, the other is the inserted cell, created by code, and provided by another array for state data
Data Source section:
myprojectcellmodel.h// Dynamic Insert Delete Row//// Created by Beyond on 14-10-18.// Copyright (c) 2014 Com.beyond All rights reserved.// list of data models used by the cell #import <Foundation/Foundation.h> @interface myprojectcellmodel:nsobject//icon @property (nonatomic,copy) nsstring *icon;//title @property (nonatomic,copy) NSString * title;//release Status @property (nonatomic,copy) nsstring *publishstatus;//date @property (nonatomic,copy) NSString *date;// How many people focus on @property (nonatomic,copy) nsstring *num;//Click on the rightmost button, what do I need to do?? A view pops up to modify the status of the publication??? class method, dictionary to object similar to JavaBean one-time padding + (Myprojectcellmodel *) Modelwithdict: (Nsdictionary *) dict;//object method, after setting the object's properties, returns the object-( Myprojectcellmodel *) Initwithdict: (Nsdictionary *) dict; @end
<span style= "color: #330033;" >//// myprojectcellmodel.m// Dynamic Insert Delete Row//// Created by Beyond on 14-10-18.// Copyright (c) 2014 Com.beyond All rights reserved.// list of data models used by the cell #import "MyProjectCellModel.h" @implementation myprojectcellmodel//class method, dictionary to object similar to JavaBean disposable fill + (Myprojectcellmodel *) Modelwithdict: (nsdictionary *) dict{ // Just call the Initwithdict method of the object, the reason is to use self for the subclass to be compatible with return [[Self alloc]initwithdict:dict];} Object method, after setting the object's properties, returns the Object-(Myprojectcellmodel *) Initwithdict: (nsdictionary *) dict{ //must first call the parent class NSObject's Init method if (self = [super init]) { //Set the object's own property [Setvaluesforkeyswithdictionary:dict]; } Returns the filled object return self ;} @end </span>
Primary cell, composed of xib and class declarations, class implementations
myprojectcell.h//Dynamic Insert Delete Row////Created by Beyond on 14-10-18.//Copyright (c) 2014 Com.beyond All rights reserved .//This is the main cell, used to display the micro-BO data cell#import <uikit/uikit.h>//define a block, the role is to click on the right button to tell the main controller pop up a View (including pause, modify, delete), The parameters of the block are (int row) typedef void (^cellrightbtnblock) (int), @class Myprojectcellmodel; @interface Myprojectcell: uitableviewcell//icon @property (nonatomic,weak) iboutlet Uiimageview *iconview;//title @property (nonatomic,weak) IBOutlet UILabel *titlelabel;//Weibo release status "Pause, draft, publish, expire" @property (nonatomic,weak) iboutlet UILabel *publishstatuslabel;// Date @property (nonatomic,weak) iboutlet UILabel *datelabel;//How many people are concerned about the number part @property (nonatomic,weak) iboutlet UILabel * numlabel;//How many people pay attention to the fixed text, no one is concerned about this microblog, will not show @property (nonatomic,weak) Iboutlet UILabel *constlabel;//A member attribute block, When the button on the right side of the cell is clicked, it is called, and a view is popped to change the status of the Weibo @property (nonatomic,copy) Cellrightbtnblock wannachangestatusblock;// Instantiate an object from Xib + (Myprojectcell *) myprojectcell;//returns the object after encapsulating the data-(Myprojectcell *) CellwithcellmoDel: (Myprojectcellmodel *) Cellmodel; @end
myprojectcell.m//Dynamic Insert Delete Row////Created by Beyond on 14-10-18.//Copyright (c) 2014 Com.beyond All rights reserved .//This is the primary cell, used to display Weibo data for Cell#import "MyProjectCell.h" #import "MyProjectCellModel.h" @implementation myprojectcell// Instantiate an object from Xib + (Myprojectcell *) myprojectcell{//Mainbundel load xib, extension does not write. Xib return [[NSBundle Mainbundle] Loadnib named:@ "Myprojectcell" Owner:nil options:nil][0];} Returns the object after encapsulating the data-(Myprojectcell *) Cellwithcellmodel: (Myprojectcellmodel *) cellmodel{//Avatar Fillet _iconview.layer.cor Nerradius = 6; _iconview.layer.maskstobounds = YES; _iconview.image = [UIImage ImageNamed:cellModel.icon]; _titlelabel.text = Cellmodel.title; _publishstatuslabel.text = Cellmodel.publishstatus; _datelabel.text = cellmodel.date; if ([_numlabel.text intvalue]) {_constlabel.hidden = YES; } else {_numlabel.text = Cellmodel.num; _constlabel.hidden = NO; }//Generate a right button to add to cell rightmost UIButton *rightbtn = [UIButton Buttonwithtype:uibuttontypecustom]; [Rightbtn setbackgroundimage:[uiimage imagenamed:@ "myprojectcellrightbtn"] forstate:uicontrolstatenormal]; Rightbtn.frame = CGRectMake (286, 0, 34, 44); [Self.contentview ADDSUBVIEW:RIGHTBTN]; Rightbtn.tag = 5267; [Rightbtn setbackgroundimage:[uiimage imagenamed:@ "Myprojectcellrightbtn.png"] forstate:uicontrolstatenormal]; [Rightbtn addtarget:self Action: @selector (rightbtnclicked:) forcontrolevents:uicontroleventtouchupinside]; return self;} Define macros, Judge Ios7#define iOS7 [[[[Uidevice currentdevice]systemversion] floatvalue] >= 7.0-(void) rightbtnclicked: ( UIButton *) sender{int row = 0; Myprojectcell *cell; UITableView *tableview; if (iOS7) {NSLog (@ "button's parent class 2:%@", [[[Sender Superview] superview] superview]); Cell = (Myprojectcell *) [[[Sender Superview] superview] superview]; NSLog (@ "Cell's parent class 2:%@", [[Cell Superview] superview]); TableView = (uitableview*) [[Cell Superview] superview]; }else{//IOS6 cell = (Myprojectcell *) [sender Superview]; NSLog (@ "Clicked cell:%@", cell); TableView = (uitableview*) [cell Superview]; } Nsindexpath *path = [TableView Indexpathforcell:cell]; row = Path.row; NSLog (@ "Parent class 1%@", [sender Superview]); NSLog (@ "Parent class 2%@", [[Sender Superview] superview]); NSLog (@ "Parent class 3%@", [[[Sender Superview] superview]superview]); NSLog (@ "Parent class 4%@", [[[[Sender Superview] superview]superview]superview]); NSLog (@ "clicked the button to the right of page%d", row); Call the block of the outside controller and pass the cell's line number past _wannachangestatusblock (row);} @end
additional cell, which is dynamically added below the main cell when you click on the Maincell button at the far right
changestatuscell.m//Dynamic Insert Delete Row////Created by Beyond on 14-10-18.//Copyright (c) 2014 Com.beyond All rights reser ved.//additional cell, dynamically added below the main cell #import "ChangeStatusCell.h" @implementation changestatuscell//when you click on the Maincell rightmost button Additional cell, no xib, created by code-(ID) Initwithstyle: (Uitableviewcellstyle) style Reuseidentifier: (NSString *) reuseidentifier{ self = [super Initwithstyle:style reuseidentifier:reuseidentifier]; if (self) {//Add three buttons and set tag UIButton *b1 = [self createbuttonwithframe:cgrectmake (0, 0, 106.5, +) Target: Self Selector: @selector (btnaction:) image:@ "Statuspause_gray.png" imagepressed:@ "Statuspause_blue.png"]; B1.tag = 1; UIButton *b2 = [Self createbuttonwithframe:cgrectmake (106.5, 0, 106.5,) target:self Selector: @selector (btnaction:) image:@ "Statusmodify_gray.png" imagepressed:@ "Statusmodify_blue.png"]; B2.tag = 2; UIButton *b3 = [Self createbuttonwithframe:cgrectmake (213, 0, 106.5,) target:self Selector: @selEctor (btnaction:) image:@ "Statustrash_gray.png" imagepressed:@ "Statustrash_blue.png"]; B3.tag = 3; Add to Contentview, otherwise you cannot receive events//For example: adding a button directly into TableView is not able to receive events, because TableView it does not pass events to any control outside its system [Self.conte Ntview ADDSUBVIEW:B1]; [Self.contentview ADDSUBVIEW:B2]; [Self.contentview ADDSUBVIEW:B3]; } return self;} -(void) Btnaction: (ID) Sender {UIButton *btn = (UIButton *) sender; Switch (btn.tag) {Case 1: {NSLog (@ ">>>>>>>>>>B1"); } break; Case 2: {NSLog (@ ">>>>>>>>>>b2"); } break; Case 3: {NSLog (@ ">>>>>>>>>>b3"); } break; Default:break; }} #pragma mark-Tool Method-(uibutton*) Createbuttonwithframe: (CGRect) frame target: (ID) Target Selector: (SEL) Selector Image: (NSString *) image imagepressed: (NSString *) imagepressed{UIButton * button = [UIButton buttonwithtype:uibuttontypecustom]; [Button Setframe:frame]; UIImage *newimage = [UIImage imagenamed:image]; [Button Setbackgroundimage:newimage Forstate:uicontrolstatenormal]; UIImage *newpressedimage = [UIImage imagenamed:imagepressed]; [Button Setbackgroundimage:newpressedimage forstate:uicontrolstatehighlighted]; [Button Addtarget:target action:selector forcontrolevents:uicontroleventtouchupinside]; return button;} @end
Controller, inherited from Uiviewcontroller, the most core part
myprojectcontroller.m//Dynamic Insert Delete Row////Created by Beyond on 14-10-18.//Copyright (c) 2014 Com.beyond All rights RE served.//Controller, the most important part #import "MyProjectController.h" #import "MyProjectCell.h" #import "ChangeStatusCell.h" #import " MyProjectCellModel.h "//very easy to use, quickly create a RECT and adapt the macro # define ISIOS7 ([[[[[[[[[[[] [[[Uidevice Currentdevice] systemversion] SUBSTRINGTOINDEX:1] intvalue]>=7) #define CGRECT_NO_NAV (X,y,w,h) CGRectMake ((x), (y+ (isios7?20:0)), (W), (h)) # Define CGRECT_HAVE_NAV (X,y,w,h) CGRectMake ((x), (y+ (isios7?64:0)), (W), (h)) #define IS_IOS7 [[[Uidevice Currentdevice] Systemversion] Floatvalue] >= 7.0@interface myprojectcontroller () <uitableviewdatasource,uitableviewdelegate >{UITableView *_tableview; Data source object array Nsmutablearray *_modelarr; An array of auxiliary state dictionaries; the same length as the modelarr above Nsmutablearray *_statusdictarr; Records the line numbers that have been expanded int _expandedmaincellrow;} @end @implementation myprojectcontroller-(void) viewdidload{[Super Viewdidload]; if (IS_IOS7) {Self.edGesforextendedlayout = Uirectedgenone; Self.extendedlayoutincludesopaquebars = NO; Self.modalpresentationcapturesstatusbarappearance = NO; }//Add TableView and set proxy and data source UITableView *tableview = [[UITableView alloc]initwithframe:cgrect_no_nav (0, 0, 320, 460) Style:uitableviewstyleplain]; Tableview.datasource = self; Tableview.delegate = self; [Self.view Addsubview:tableview]; _tableview = TableView; _expandedmaincellrow =-1; Provides an array of data models _modelarr = [Nsmutablearray array]; An array that records the primary cell and additional cells and the attached state, both of which are the same length _statusdictarr = [Nsmutablearray array]; Load the data source [self loaddata];} #pragma mark-Initialize data-(void) loaddata{nsstring *filepath = [[NSBundle mainbundle]pathforresource:@ ' myprojectlist.plist ' Oftype:nil]; Nsarray *temparr = [Nsarray Arraywithcontentsoffile:filepath]; Very IMPORTANT!!!!!!! For state arrays only use nsdictionary *statusdict = @{@ "Cell": @ "Myprojectcell", @ "isattached": @ (N O) }; For (Nsdictionary *dict in Temparr) {Myprojectcellmodel *model = [Myprojectcellmodel modelwithdict:dict]; [_modelarr Addobject:model]; [_statusdictarr addobject:statusdict]; }} #pragma Mark-tableview proxy method//Cancel the default click on the cell's selected effect-(void) TableView: (UITableView *) TableView Didselectrowatindexpath: ( Nsindexpath *) indexpath{[TableView Deselectrowatindexpath:indexpath animated:yes];} Row height-(cgfloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) indexpath{return 44;} #pragma mark-tableview data source//Total number of rows-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (Nsinteger) section{return _statusdictarr.count;} Core method; Create a cell in a case, or populate a data model for a cell-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: ( Nsindexpath *) indexpath{if ([[[_statusdictarr[indexpath.row] objectforkey:@ "Cell"] isequaltostring:@ "MyProjectCell" ]) {static NSString *cellid_1 = @ "Myprojectcell"; MyProjectcell *cell = [TableView dequeuereusablecellwithidentifier:cellid_1]; if (cell = = nil) {cell = [Myprojectcell Myprojectcell]; Cell.selectionstyle = Uitableviewcellselectionstylegray; __unsafe_unretained Myprojectcontroller *blockctroller = self; Cell.wannachangestatusblock = ^ (int row) {NSLog (@ "Controller gets the line number of the cell clicked:%d", row); Call the controller's method to show or hide the View [Blockctroller Showhidechangestatusview:row] used to change the state; }; }//Pass data source//Set unique content in cell int temprow = Indexpath.row; if (_expandedmaincellrow! =-1 && indexpath.row > _expandedmaincellrow) {temprow = Indexpath.row- 1; }//If this method is called because the row that you just expanded is closed, it is not expanded, or the data model is taken from the original location if (_expandedmaincellrow = =-1) {Temprow = Indexpath.row; } Myprojectcellmodel *model = [_modelarr objectatindex:temprow]; cell = [Cell Cellwithcellmodel: Model]; return cell; }else if ([[[_statusdictarr[indexpath.row] objectforkey:@ "Cell"] isequaltostring:@ "Changestatuscell"]) {static NSStri ng *cellid_2 = @ "Changestatuscell"; Changestatuscell *cell = [TableView dequeuereusablecellwithidentifier:cellid_2]; if (cell = = nil) {cell = [[Changestatuscell alloc]initwithstyle:uitableviewcellstyledefault Reuseidentifier:ce Llid_2]; Cell.selectionstyle = Uitableviewcellselectionstylenone; } return cell; } return nil;} -(void) scrollviewwillbegindragging: (Uiscrollview *) scrollview{//Start scrolling before closing the already expanded Attachrow} #pragma mark- Call//Show or hide view-(void) Showhidechangestatusview: (int) row{if (row = = _expandedmaincellrow) when clicking on the rightmost button of the cell If the clicked line is already an open line, close directly and return to [self closeoneexpandedcell:_expandedmaincellrow]; }else{if (_expandedmaincellrow = =-1) {//Represents never unfolded, first unfolded [self expandonerow:row]; } else {//If the row for this click has not been expanded, first close the last expanded row, and then expand the row//special Note that this row number contains the expanded Attachcell, so subtract 1; the line number is the line number in Modelarr if (_expandedmaincellrow < row) {//expanded line, above; row in new click is below row = row-1; } [self closeoneexpandedcell:_expandedmaincellrow]; [Self expandonerow:row]; }}//closes a specified row of expandedcell-(void) Closeoneexpandedcell: (int) row{//Because there is no expanded line after this operation completes, so first clear 0; must first clear 0 ~ ~ ~ because TA The Cellforrow method is called in the Bleviewupdate method _expandedmaincellrow =-1; If line No. 0 is already attached, close the additional cell nsdictionary * dic = @{@ "cell": @ "Myprojectcell" @ "isattached": @ (NO)}; The bool in the main cell reverts to no _statusdictarr[row] = dic; NSLog (@ "Delete before:%d", [_statusdictarr Count]); The Attchedcell at the next position in the primary cell array is removed [_statusdictarr removeobjectatindex:row+1]; NSLog (@ "deleted:%d", [_statusdictarr Count]); [_tableview beginupdates]; Nsindexpath *path = [Nsindexpath indexpathforrow:row+1 insection:0]; [_tableview Deleterowsatindexpaths:@[paTH] withrowanimation:uitableviewrowanimationmiddle]; [_tableview endupdates]; }//records and expands the specified line (the order must not be reversed)-(void) Expandonerow: (int) row{_expandedmaincellrow = row; If the additional cell is not open on line No. 0, open the additional cell nsdictionary * dic = @{@ "Cell": @ "Myprojectcell", @ "isattached": @ (YES)}; Modify the primary cell's status word isattached yes _statusdictarr[row] = dic; Insert a new Changestatuscell into the array nsdictionary * adddic = @{@ "Cell": @ "Changestatuscell", @ "isattached": @ (YES)}; [_statusdictarr insertobject:adddic Atindex:row + 1]; [_tableview beginupdates]; Nsindexpath *path = [Nsindexpath Indexpathforrow:row + 1 insection:0]; [_tableview Insertrowsatindexpaths:@[path] withrowanimation:uitableviewrowanimationmiddle]; [_tableview endupdates]; if (row = = _modelarr.count-1) {//If the last line is expanded, also let TableView scroll up 44 of the height [self showexpandedcellforlastrow]; }}//if the last line is expanded, also let TableView scroll up 44 of the height-(void) showexpandedcellforlastrow{nsindexpath *path = [Nsindexpath Indexpathforrow:_modeLarr.count insection:0]; [_tableview Scrolltorowatindexpath:path atscrollposition:uitableviewscrollpositionmiddle Animated:YES];} @end
Ios_ dynamically inserting deleted rows