Implementation of the cell multiple-selection feature of Swift TableView (get multiple selections, multiple-selection deletes)

Source: Internet
Author: User
Tags uikit

Sometimes we need to use the multiple-selection function of table (TableView) in our application. In fact, TableView has a variety of multiple-selection features, without the use of Third-party components can also be implemented. The following are described separately.

Method 1, customize an array to hold the index of the selected item (non-edit state)

(1) We first define an array, and when the table is not edited, click a cell to add its index to the array. Also tick the end of the cell to indicate the selected state. Click the original selected cell again, uncheck the state, and remove the index from the array.

(2) Click the "OK" button on the navigation bar to get the index of all the selected items and the corresponding values, and print them out.


Import Uikit

Class Viewcontroller:uiviewcontroller, Uitableviewdelegate, Uitableviewdatasource {

var items:[string] = ["Entry 1", "Entry 2", "Entry 3", "Entry 4", "Entry 5"]

Store index of selected cells
var selectedindexs = [Int] ()

var tableview:uitableview?

Override Func Loadview () {
Super.loadview ()
}

Override Func Viewdidload () {
Super.viewdidload ()

Create a table view
Self.tableview = UITableView (Frame:self.view.frame, Style:UITableViewStyle.Plain)
self.tableview!. delegate = Self
self.tableview!. DataSource = Self
To create a reused cell
self.tableview!. RegisterClass (Uitableviewcell.self,
Forcellreuseidentifier: "Swiftcell")
Self.view.addSubview (self.tableview!)
}

In this case, there is only one partition
Func Numberofsectionsintableview (Tableview:uitableview)-> Int {
return 1;
}

Returns the number of table rows (that is, returns the number of controls)
Func TableView (Tableview:uitableview, numberofrowsinsection section:int)-> Int {
Return Self.items.count
}

Create each cell display (create a parameter indexpath a specified cell)
Func TableView (Tableview:uitableview, Cellforrowatindexpath Indexpath:nsindexpath)
-> UITableViewCell
{
In order to provide tabular display performance, the completed cells need to be reused
Let identify:string = "Swiftcell"
Cells in the same form are reused and registered at the time of declaration
Let cell = Tableview.dequeuereusablecellwithidentifier (Identify,
Forindexpath:indexpath) as UITableViewCell

Cell.textlabel? Text = Self.items[indexpath.row]

Decide whether to select (check the end of the cell)
If Selectedindexs.contains (Indexpath.row) {
Cell.accessorytype = Uitableviewcellaccessorytype.checkmark
} else {
Cell.accessorytype = Uitableviewcellaccessorytype.none
}

return cell
}

Uitableviewdelegate method to handle selected events for list items
Func TableView (Tableview:uitableview, Didselectrowatindexpath Indexpath:nsindexpath) {
Determines whether the line was previously selected
If Let index = Selectedindexs.indexof (indexpath.row) {
Selectedindexs.removeatindex (Index)//original checked unchecked
}else{
Selectedindexs.append (Indexpath.row)//The original selection is not selected
}

Refresh the row
Self.tableview? Reloadrowsatindexpaths ([Indexpath], withrowanimation:. Automatic)
}

OK button click
@IBAction func Btnclick (sender:anyobject) {
Print (Index of selected items is:, Selectedindexs)
Print (the value of the selected item is:)
For index in Selectedindexs {
Print (Items[index])
}
}

Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
}
}

Method 2, set Allowsmultipleselection to True (non-edit state)

In the preceding example, the table is actually a radio. It's just that we've defined a number to hold the selected cell index to achieve multiple selections.

The following is the same functionality, except that this time the table is set to allow multiple selections (Allowsmultipleselection is true), so that we do not have to define an array to store the selected index.


Import Uikit

Class Viewcontroller:uiviewcontroller, Uitableviewdelegate, Uitableviewdatasource {

var items:[string] = ["Entry 1", "Entry 2", "Entry 3", "Entry 4", "Entry 5"]

var tableview:uitableview?

Override Func Loadview () {
Super.loadview ()
}

Override Func Viewdidload () {
Super.viewdidload ()

Create a table view
Self.tableview = UITableView (Frame:self.view.frame, Style:UITableViewStyle.Plain)
self.tableview!. delegate = Self
self.tableview!. DataSource = Self
To create a reused cell
self.tableview!. RegisterClass (Uitableviewcell.self,
Forcellreuseidentifier: "Swiftcell")
Self.view.addSubview (self.tableview!)

Set Allow cell multiple selections
self.tableview!. Allowsmultipleselection = True
}

In this case, there is only one partition
Func Numberofsectionsintableview (Tableview:uitableview)-> Int {
return 1;
}

Returns the number of table rows (that is, returns the number of controls)
Func TableView (Tableview:uitableview, numberofrowsinsection section:int)-> Int {
Return Self.items.count
}

Create each cell display (create a parameter indexpath a specified cell)
Func TableView (Tableview:uitableview, Cellforrowatindexpath Indexpath:nsindexpath)
-> UITableViewCell
{
In order to provide tabular display performance, the completed cells need to be reused
Let identify:string = "Swiftcell"
Cells in the same form are reused and registered at the time of declaration
Let cell = Tableview.dequeuereusablecellwithidentifier (Identify,
Forindexpath:indexpath) as UITableViewCell
Cell.textlabel? Text = Self.items[indexpath.row]
return cell
}

Handling selected events for list items
Func TableView (Tableview:uitableview, Didselectrowatindexpath Indexpath:nsindexpath) {
Let cell = Self.tableview? Cellforrowatindexpath (Indexpath)
Cell?. Accessorytype =. Checkmark
}

To handle the unchecked event of a list item
Func TableView (Tableview:uitableview,
Diddeselectrowatindexpath Indexpath:nsindexpath) {
Let cell = Self.tableview? Cellforrowatindexpath (Indexpath)
Cell?. Accessorytype =. None
}

OK button click
@IBAction func Btnclick (sender:anyobject) {
var selectedindexs = [Int] ()

If let SelectedItems = tableview!. indexpathsforselectedrows {
For Indexpath in SelectedItems {
Selectedindexs.append (Indexpath.row)
}
}

Print (Index of selected items is:, Selectedindexs)
Print (the value of the selected item is:)
For index in Selectedindexs {
Print (Items[index])
}
}

Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
}
}

Method 3,allowsmultipleselectionduringediting set to True (edit state)
This sample is somewhat similar to the one above, except that the table can be selected in edit mode.
(1) The following sample table cannot be selected by default.
(2) long by the table into the edit state, when the cell appears in front of the selection box. Click to select and cancel the cell.
(3) Click the "Delete" button on the navigation bar to remove all selected cells.


Import Uikit

Class Viewcontroller:uiviewcontroller, Uitableviewdelegate, Uitableviewdatasource,
uigesturerecognizerdelegate {

var items:[string] = ["Entry 1", "Entry 2", "Entry 3", "Entry 4", "Entry 5"]

var tableview:uitableview?

Override Func Loadview () {
Super.loadview ()
}

Override Func Viewdidload () {
Super.viewdidload ()

Create a table view
Self.tableview = UITableView (Frame:self.view.frame, Style:UITableViewStyle.Plain)
self.tableview!. delegate = Self
self.tableview!. DataSource = Self
To create a reused cell
self.tableview!. RegisterClass (Uitableviewcell.self,
Forcellreuseidentifier: "Swiftcell")
Self.view.addSubview (self.tableview!)

Table allows multiple selections in edit state
Self.tableview? Allowsmultipleselectionduringediting = True

Binding to long-pressed responses
Let longpress = Uilongpressgesturerecognizer (target:self,
Action: #selector (Viewcontroller.tableviewcelllongpressed (_:))
Agent
Longpress.delegate = Self
Longpress.minimumpressduration = 1.0
Add a long gesture to the view where you want to implement a long action
self.tableview!. Addgesturerecognizer (longpress)
}

Cell length response by event
Func tableviewcelllongpressed (Gesturerecognizer:uilongpressgesturerecognizer)
{
if (gesturerecognizer.state = = uigesturerecognizerstate.ended)
{
Print ("uigesturerecognizerstateended");
Switch between normal and edit states
if (self.tableview!. editing = = False) {
self.tableview!. Setediting (True, animated:true)
}
else {
self.tableview!. Setediting (False, Animated:true)
}
}
}

In this case, there is only one partition
Func Numberofsectionsintableview (Tableview:uitableview)-> Int {
return 1;
}

Returns the number of table rows (that is, returns the number of controls)
Func TableView (Tableview:uitableview, numberofrowsinsection section:int)-> Int {
Return Self.items.count
}

Create each cell display (create a parameter indexpath a specified cell)
Func TableView (Tableview:uitableview, Cellforrowatindexpath Indexpath:nsindexpath)
-> UITableViewCell
{
In order to provide tabular display performance, the completed cells need to be reused
Let identify:string = "Swiftcell"
Cells in the same form are reused and registered at the time of declaration
Let cell = Tableview.dequeuereusablecellwithidentifier (Identify,
Forindexpath:indexpath) as UITableViewCell
Cell.textlabel? Text = Self.items[indexpath.row]
return cell
}

Delete button click
@IBAction func Btnclick (sender:anyobject) {
Get the Check index
var selectedindexs = [Int] ()
If let SelectedItems = tableview!. indexpathsforselectedrows {
For Indexpath in SelectedItems {
Selectedindexs.append (Indexpath.row)
}
}

Delete the selected data
Items.removeatindexes (Selectedindexs)
Reload data
Self.tableview? Reloaddata ()
Exit Edit Status
self.tableview!. Setediting (False, Animated:true)
}

Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
}
}

Extension Array {
Array method extension, supporting deletion based on an indexed array
mutating func removeatindexes (ixs: [Int]) {
For I in Ixs.sort (>) {
Self.removeatindex (i)
}
}
}

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.