IOS _ dynamically insert and delete rows, ios dynamically insert and delete rows

Source: Internet
Author: User

IOS _ dynamically insert and delete rows, ios dynamically insert and delete rows
Finally:

It is divided into three layers of MVC design; there are two types of custom cells; one is MainCell, which is provided by ModelArr; the other is the inserted Cell, which is created by code, and the status data is supplied by another array.
Data Source section:

/// MyProjectCellModel. h // dynamically insert and delete rows /// Created by beyond on 14-10-18. // Copyright (c) 2014 com. beyond All rights reserved. // data model used by the cell in the list # import <Foundation/Foundation. h> @ interface MyProjectCellModel: NSObject // icon @ property (nonatomic, copy) NSString * icon; // title @ property (nonatomic, copy) NSString * title; // publish status @ property (nonatomic, copy) NSString * publishStatus; // Date @ property (nonatomic, copy) N SString * date; // how many followers @ property (nonatomic, copy) NSString * num; // What operations do I need to perform when I click the rightmost button ?? A View is displayed to modify the publishing status ??? // Class method. The dictionary-to-object conversion method is similar to javaBean one-time filling + (MyProjectCellModel *) modelWithDict :( NSDictionary *) dict; // object method. After setting the object attributes, returned object-(MyProjectCellModel *) initWithDict :( NSDictionary *) dict; @ end

<Span style = "color: #330033;"> /// MyProjectCellModel. m // dynamically insert and delete rows /// Created by beyond on 14-10-18. // Copyright (c) 2014 com. beyond All rights reserved. // data model used by the cell in the list # import "MyProjectCellModel. h "@ implementation MyProjectCellModel // class method. The dictionary object is similar to the one-time filling + (MyProjectCellModel *) modelWithDict :( NSDictionary *) dict {// only calls the initWithDict method of the object, self is used to ensure compatibility with the subclass. return [[self alloc] initWithDict: dict];} // object method. After setting the object attributes, the object-(MyProjectCellModel *) is returned *) initWithDict :( NSDictionary *) dict {// The init method of the parent NSObject must be called first if (self = [super init]) {// set the attributes of the object [self setValuesForKeysWithDictionary: dict] ;}// return the filled object return self ;}@ end </span>


Main Cell, composed of xib, class declaration, and class implementation

/// MyProjectCell. h // dynamically insert and delete rows /// Created by beyond on 14-10-18. // Copyright (c) 2014 com. beyond All rights reserved. // This is the main Cell used to display the Cell # import <UIKit/UIKit. h> // define a block. click the button on the Right To tell the master controller to bring up a View (including pause, modification, and deletion). The block parameter is (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; // publish status of Weibo [pause, draft, publish, and expire] @ property (nonatomic, weak) IBOutlet UILabel * publishStatusLabel; // Date @ property (nonatomic, weak) IBOutlet UILabel * dateLabel; // number of followers @ property (nonatomic, weak) IBOutlet UILabel * numLabel; // The fixed number of characters followed. If no one pays attention to this microblog, @ property (nonatomic, weak) IBOutlet UILabel * constLabel will not be displayed; // a member attribute block, when the button on the right of the cell is clicked, a view will pop up to change the Weibo status @ property (nonatomic, copy) cellRightBtnBlock wannaChangeStatusBlock; // load and instantiate an object from xib + (MyProjectCell *) myProjectCell; // return the object after encapsulated data-(MyProjectCell *) cellWithCellModel :( MyProjectCellModel *) cellModel; @ end


/// MyProjectCell. m // dynamically insert and delete rows /// Created by beyond on 14-10-18. // Copyright (c) 2014 com. beyond All rights reserved. // This is the main Cell used to display the Cell # import "MyProjectCell. h "# import" MyProjectCellModel. h "@ implementation MyProjectCell // load and instantiate an object from xib + (MyProjectCell *) myProjectCell {// mainBundel load xib, no need to write extension. xib return [[NSBundle mainBundle] loadNibNamed: @ "MyProjectCell" owner: nil options: nil] [0];} // return the object after encapsulated data-(MyProjectCell *) cellWithCellModel :( MyProjectCellModel *) cellModel {// Avatar rounded corner _ iconView. layer. cornerRadius = 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 button on the right to add it to the rightmost cell UIButton * rightBtn = [UIButton buttonWithType: bytes]; [rightBtn setBackgroundImage: [UIImage imageNamed: @ "MyProjectCellRightBtn"] forState: UIControlStateNormal]; rightBtn. frame = CGRectMake (286, 0, 34, 44); [self. contentView addSubview: rightBtn]; rightBtn. tag = 5267; [rightBtn failed: [UIImage imageNamed: @ "success"] forState: UIControlStateNormal]; [rightBtn addTarget: self action: @ selector (rightBtnClicked :) forControlEvents: Success]; return self;} // define the macro to 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 parent class 2: % @", [[sender superview]); cell = (MyProjectCell *) [[[sender superview]; NSLog (@ "cell parent class 2: % @ ", [[cell superview]); tableView = (UITableView *) [[cell superview];} else {// iOS6 cell = (MyProjectCell *) [sender superview]; NSLog (@ "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]); NSLog (@ "parent class 3% @", [[[sender superview]); NSLog (@ "parent class 4% @", [[[sender superview]); NSLog (@ "click the button on the Right of row % d", row ); // call the block of the external controller and pass the row number of the cell to the past _ wannaChangeStatusBlock (row);} @ end


When you click the button on the rightmost side of the MainCell, It is dynamically added under the main Cell.
//// ChangeStatusCell. m // dynamically insert and delete rows /// Created by beyond on 14-10-18. // Copyright (c) 2014 com. beyond All rights reserved. // The attached Cell. When you click the button at the rightmost of the MainCell, It is dynamically added under the main Cell # import "ChangeStatusCell. h "@ implementation ChangeStatusCell // additional cell, no xib, created by the 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, 44) Target: self Selector: @ selector (btnAction :) Image: @ "reported" ImagePressed: @ "StatusPause_blue.png"]; b1.tag = 1; UIButton * b2 = [self createButtonWithFrame: CGRectMake (106.5, 0,106.5, 44) Target: self Selector: @ selector (btnAction :) Image: @ "reported" ImagePressed: @ "StatusModify_blue.png"]; b2.tag = 2; UIButton * b3 = [self createButtonWithFrame: CGRectMake (213, 0,106.5, 44) Target: self Selector: @ selector (btnAction :) Image: @ "StatusTrash_gray.png" ImagePressed: @ "StatusTrash_blue.png"]; b3.tag = 3; // Add to contentView; otherwise, events cannot be received. // For example, adding a button directly to tableView cannot receive events; because tableView does not pass events to any controls outside of its system [self. contentView 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: Success]; [button setFrame: frame]; UIImage * newImage = [UIImage imageNamed: image]; [button failed: 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 core part
/// MyProjectController. m // dynamically insert and delete rows /// Created by beyond on 14-10-18. // Copyright (c) 2014 com. beyond All rights reserved. // controller, the most important part # import "MyProjectController. h "# import" MyProjectCell. h "# import" ChangeStatusCell. h "# import" MyProjectCellModel. h "// very useful. quickly create a rect macro and adapt to it # define IsIOS7 ([[[UIDevice currentDevice] systemVersion] substringToIndex: 1] intValue]> = 7) # define CGRECT_NO_NAV (x, y, w, h) CG RectMake (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 auxiliary state dictionary array; the length is the same as that of modelArr above. NSMutableArray * _ statusDictArr; // record the expanded row number int _ ExpandedMainCellRow;} @ end @ implementation MyProjectController-(void) viewDidLoad {[s Uper viewDidLoad]; if (IS_IOS7) {self. edgesForExtendedLayout = UIRectEdgeNone; self. extendedLayoutIncludesOpaqueBars = NO; self. activities = NO;} // Add tableView and set the 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 addSubv Iew: tableView]; _ tableView = tableView; _ ExpandedMainCellRow =-1; // provides an array of data models _ modelArr = [NSMutableArray array]; // an array used to record the primary Cell, the additional Cell, and the additional status; the two have 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 arrayWithContents OfFile: filePath]; // very important !!!!!!! NSDictionary * statusDict = @ {@ "Cell": @ "MyProjectCell", @ "isAttached": @ (NO)}; for (NSDictionary * dict in tempArr) {MyProjectCellModel * model = [MyProjectCellModel modelWithDict: dict]; [_ modelArr addObject: model]; [_ statusDictArr addObject: statusDict];} # pragma mark-TableView proxy method // deselect the selected Result of the default click cell-(void) tableView :( UITableView *) tableView didSelectRowAtIndexPath :( NSIndexPath *) indexP Ath {[tableView deselectRowAtIndexPath: indexPath animated: YES];} // high-(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;} // The core method; create a cell by situation; or fill the data model of the cell-(UITableViewCell *) tableView :( UITableV Iew *) tableView cellForRowAtIndexPath :( NSIndexPath *) indexPath {if ([[_ statusDictArr [indexPath. row] objectForKey: @ "Cell"] isEqualToString: @ "MyProjectCell"]) {static NSString * cel1__1 = @ "MyProjectCell"; MyProjectCell * cell = [tableView sequence: cel1__1]; if (cell = nil) {cell = [MyProjectCell myProjectCell]; cell. selectionStyle = UITableViewCellSelectionStyleGray; _ u NSAID fe_unretained MyProjectController * blockCtroller = self; cell. wannaChangeStatusBlock = ^ (int row) {NSLog (@ "Get the row number of the cell to be clicked in the Controller: % d", row); // call the Controller method, display or hide the view [blockCtroller showHideChangeStatusView: row] ;}}// transfer the data source // set the unique content in the cell int tempRow = indexPath. row; if (_ ExpandedMainCellRow! =-1 & indexPath. row> _ ExpandedMainCellRow) {tempRow = indexPath. row-1;} // If the expanded row is closed, this method is called; otherwise, or take the data model 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: @ "ChangeStatusC Ell "]) {static NSString * cel%_2 = @" ChangeStatusCell "; ChangeStatusCell * cell = [tableView dequeueReusableCellWithIdentifier: cel%_2]; if (cell = nil) {cell = [[ChangeStatusCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: cel%_2]; cell. selectionStyle = UITableViewCellSelectionStyleNone;} return cell;} return nil;}-(void) scrollViewWillBeginDragging :( UIScrollView *) scro LlView {// close the expanded AttachRow before rolling start} # pragma mark-call // display or hide the view used to change the status when the rightmost button of the cell is clicked) showHideChangeStatusView :( int) row {if (row = _ ExpandedMainCellRow) {// if the row to be clicked is already an opened row, close it directly and return [self closeOneExpandedCell: _ ExpandedMainCellRow];} else {if (_ ExpandedMainCellRow =-1) {// indicates that it has never been expanded. Expand [self expandOneRow: row] for the first time;} else {// If the row to be clicked has not been expanded, close the expanded row first, and then expand the opened row. // pay special attention to this, this row number contains the expanded TachCell. Therefore, 1 is subtracted. The row number in modelArr is the expanded row in if (_ ExpandedMainCellRow <row; row = row-1;} [self closeOneExpandedCell: _ ExpandedMainCellRow]; [self expandOneRow: row] ;}} // close the ExpandedCell-(void) closeOneExpandedCell :( int) row {// The unexpanded row is not displayed after this operation is completed, so it must be cleared first; must be cleared first ~~~~ Because the cellForRow method _ ExpandedMainCellRow =-1 will be called in the tableViewupdate method; // If row 0th is already appended, disable the additional cell NSDictionary * dic =@{ @ "Cell ": @ "MyProjectCell", @ "isAttached": @ (NO)}; // The bool in the primary Cell is restored to NO _ statusDictArr [row] = dic; NSLog (@ "before deletion: % d ", [_ statusDictArr count]); // Delete AttchedCell at the next position in the primary Cell array [_ statusDictArr removeObjectAtIndex: row + 1]; NSLog (@ "delete: % d", [_ statusDictArr count]); [_ tableView beginUpdates]; NSIndexPath * path = [NSIndexPath indexPathForRow: row + 1 inSection: 0]; [_ tableView deleteRowsAtIndexPaths: @ [path] withRowAnimation: UITableViewRowAnimationMiddle]; [_ tableView endUpdates];} // record and expand the specified row (the sequence cannot be reversed)-(void) expandOneRow :( int) row {_ ExpandedMainCellRow = row; // if the additional cell is not opened in row 0th, enable the additional cell NSDictionary * dic ={ @ "Cell ": @ "MyProjectCell", @ "isAttached": @ (YES)}; // modify the status word "isAttached" to yes _ statusDictArr [row] = dic; // Insert a new ChangeStatusCell to 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 row is displayed, You Need To scroll up the height of table view 44 [self showExpandedCellForLastRow];} // if the last row is displayed, also let tableView scroll up to 44 height-(void) showExpandedCellForLastRow {NSIndexPath * path = [NSIndexPath indexPathForRow: _ modelArr. count inSection: 0]; [_ tableView scrollToRowAtIndexPath: path atScrollPosition: UITableViewScrollPositionMiddle animated: YES];} @ end





Js dynamically inserts a row before the total row and adds the delete button for each row to delete the current row.

When you traverse the output database information, just add the modify/delete button.
 
Create a one-way Dynamic Linked List and insert, delete, and input it, including the following tasks:

# Include <stdio. h>
# Define LEN sizeof (struct number)
Struct number/* definition number and number */
Int name;
Int num;
Struct number * next;
};

Struct number * create ()/* create a linked list function */
{
Struct number * head, * new, * tail, * p;
Int count = 0;
While (1)
{
New = (struct number *) malloc (LEN );
Printf ("input Name and Number \ n ");
Scanf ("% d", & new-> name, new-> num);/* user input number and number */
If (new-> name = 0)
{
Free (new );
Break;
}
Else if (count = 0)
{
Head = new;
Tail = new;
}
Else
{
Tail-> next = new;
Tail = new;
}
Count ++;
}
Tail-> next = NULL;
Return (head );
}

Struct number * delist (struct number * head, int name)/* function for deleting numbers */
{
Struct number * p0, * p1;
P1 = head;
If (head = NULL)
{
Printf ("\ nempty list! \ N ");
}
Else
If (p1-> name = name)/* Find the same number */
Head = p1-> next;
Else
{
While (p1-> name! = Name & p1-> next! = NULL)/* troubleshoot one by one */
{
P0 = p1;
P1 = p1-> next;
}
If (p1-> name = name)
{
P0-> next = p1-> next;
Printf ("The node is deleted \ n ");
}
Else
Printf ("The node can not been foud! \ N ");
}
Return head;
}

Struct number * insert (struct number * head, struct number * new)
{... Remaining full text>

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.