简体   繁体   中英

How to convert multiple cell selection to single cell selection using Swift

In myscenario, I am trying to create single cell selection checkmark at a time. I used below code for multiple cell selection with isSelected Bool value for selection cell persistent. Now, how to convert below code for single cell selection .

My Code Below

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
    let item = self.titleData[indexPath.row]
    cell.textLabel?.text = item.title
    cell.accessoryType = item.isSelected ? .checkmark : .none
    return cell
}

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        titleData[indexPath.row].isSelected.toggle()
        tableView.reloadRows(at: [indexPath], with: .none)
        let selectedTitle = titleData.filter{$0.isSelected}
        print("\(selectedTitle)")
    }

First, in viewDidLoad(), make your tableView to allow single selection only. like this:

yourTableView.allowsMultipleSelection = false 

then you can use didSelectRowAt and didDeselectRowAt for this. This will enable only one selection at a time.

// assign isSelected true and accessoryType to checkmark

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath)
    self.titleData[indexPath.row].isSelected = true
    let selectedTitle = self.titleData[indexPath.row].title
    cell.accessoryType = .checkmark

}

// assign isSelected false and accessoryType to none

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath)
    self.titleData[indexPath.row].isSelected = false
    cell.accessoryType = .none
}

You need to maintain global variable because if you want to manage using your array you need to reset isSelected bit of array every time before you do selection.

var isSelected = false
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
        let item = self.titleData[indexPath.row]
        cell.textLabel?.text = item.title
        cell.accessoryType = isSelected ? .checkmark : .none
        return cell
     }
     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

         isSelected = true
        tableView.reloadData()

     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM