Swift-editing functions for tables (add, delete)

Source: Internet
Author: User

Table (TableView) is indeed a very useful control, now to implement an editing feature implementation, including adding and deleting, deleting include long press DELETE and left slide delete

As follows:

The specific code is as follows:

1, create the table (this table has 2 areas, with the district head and the end of the area), and the long-press gesture method binding

classtenthviewcontroller:uiviewcontroller,uitableviewdelegate,uitableviewdatasource,uigesturerecognizerdelegate {        varTableview:uitableview?varOnearray =Nsmutablearray ()varTwoarray =Nsmutablearray ()varArray =Nsmutablearray ()varHadheaders:[string]?Overridefunc viewdidload () {super.viewdidload ()//Do any additional setup after loading the view.Self.view.backgroundColor =Uicolor.whitecolor () self.title="editing functions for tables (delete, insert)"Inittabelview () Onearray= ["1","2","3"]; Twoarray= [" One"," Both","three"]; Array.addobjectsfromarray ([Onearray,twoarray])} func Inittabelview () {Let Headerlab=UILabel () headerlab.frame= CGRectMake (0,0, Screen_width, -) Headerlab.backgroundcolor=Uicolor.orangecolor () Headerlab.textcolor=Uicolor.whitecolor () headerlab.numberoflines=0Headerlab.linebreakmode=nslinebreakmode.bywordwrapping Headerlab.text="This is a table head ."Headerlab.font= Uifont.systemfontofsize ( -) Let Footerlab=UILabel () footerlab.frame= CGRectMake (0,0, Screen_width, -) Footerlab.backgroundcolor=Uicolor.orangecolor () Footerlab.textcolor=Uicolor.whitecolor () footerlab.numberoflines=0Footerlab.linebreakmode=nslinebreakmode.bywordwrapping Footerlab.text="This is a footer ."Footerlab.font= Uifont.systemfontofsize ( -) Self.hadheaders= [                        "This is the first district .",            "This is the second district ."] TableView=UITableView (frame:self.view.frame, style:. Plain) TableView!. RowHeight = -TableView!.Delegate=Self tableView!. DataSource =Self tableView?. Tablefooterview =Footerlab TableView?. Tableheaderview =Headerlab Self.view.addSubview (TableView!)                //register a cell for reuseTableView?. RegisterClass (Uitableviewcell.self, Forcellreuseidentifier:"Swiftcells")                //binding a response to a long pressLet longpress =Uilongpressgesturerecognizer (target:self,action: #selector (Tableviewcelllongpressed (_:)))//AgentLongpress.Delegate=Self longpress.minimumpressduration=1.0        //add a long-tap gesture to a view that needs to implement a long-press operationself.tableview!. Addgesturerecognizer (longpress)}

2, long press the implementation of the deleted response method

func tableviewcelllongpressed (gesturerecognizer:uilongpressgesturerecognizer) {ifGesturerecognizer.state = =Uigesturerecognizerstate.began {print ("Start")        }                ifGesturerecognizer.state = =uigesturerecognizerstate.changed {print ("have chosen")        }                ifGesturerecognizer.state = =uigesturerecognizerstate.ended {print ("End")                        //toggle between Normal and edit states            ifTableView?. editing = =false{TableView?. Setediting (true, Animated:true)            }Else{TableView?. Setediting (false, Animated:true)            }        }            }

3. Implementation of form-specific proxy method

Func Numberofsectionsintableview (Tableview:uitableview)Int {returnArray.count} func TableView (Tableview:uitableview, numberofrowsinsection section:int)-Int {returnarray.objectatindex (section). Count}//Set the area headerFunc TableView (Tableview:uitableview, Titleforheaderinsection section:int), String? {                varheaders = self.hadheaders!returnHeaders[section]} func tableView (Tableview:uitableview, Cellforrowatindexpath Indexpath:nsindexpath) -UITableViewCell {Let identify:string="Swiftcells"Let cell= Tableview.dequeuereusablecellwithidentifier (Identify,forindexpath:indexpath) asUITableViewCell Cell.selectionstyle=Uitableviewcellselectionstyle.none Cell.accessorytype=Uitableviewcellaccessorytype.disclosureindicator Cell.textlabel?. Text = Array.objectatindex (indexpath.section). Objectatindex (Indexpath.row) as?StringreturnCell} func tableView (Tableview:uitableview, Didselectrowatindexpath Indexpath:nsindexpath) { Tableview.deselectrowatindexpath (Indexpath, animated:true) Let Itemstring=Array[indexpath.section][indexpath.row] Let Alertview=Uialertview () alertview.title="Tips"Alertview.message="you have chosen \ (itemstring)"Alertview.addbuttonwithtitle ("Determine") Alertview.show ()} func TableView (Tableview:uitableview, Editingstyleforrowatindexpath Indexpath: Nsindexpath)-Uitableviewcelleditingstyle {//The first area is the insert operation, and the second one is the delete operation        ifIndexpath.section = =1 {                        returnUitableviewcelleditingstyle.insert//Insert        }                returnUitableviewcelleditingstyle.delete//Delete    }        //the specific implementation of the left slip deletionfunc TableView (Tableview:uitableview, Commiteditingstyle Editingstyle:uitableviewcelleditingstyle, Forrowatindexpath Indexpath:nsindexpath) {ifEditingstyle = =uitableviewcelleditingstyle.delete {array[indexpath.section].removeobjectatindex (indexPath.ro W) tableview.reloaddata () tableview.setediting (true, Animated:true)                    }Else ifEditingstyle = =Uitableviewcelleditingstyle.insert {array[indexpath.section].insertobject ("Insert a new", AtIndex:indexPath.row +1) Tableview.reloaddata ()}}

This will achieve the effect!

Swift-editing functions for tables (add, delete)

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.