ios uitableview swift checkmark

ios - La casilla de verificación UITableViewCell para activarse y desactivarse cuando se toca



swift checkmark (6)

Estoy trabajando en una tabla vista

Quiero poder tocar cada celda y cuando se toca, muestra una marca de verificación en la celda

Ahora tengo un código que hace que esto funcione:

// checkmarks when tapped func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let section = indexPath.section let numberOfRows = tableView.numberOfRowsInSection(section) for row in 0..<numberOfRows { if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section)) { cell.accessoryType = row == indexPath.row ? .Checkmark : .None } } }

pero este código solo selecciona 1 celda dentro de una sección (tengo 5 secciones)

Lo necesito para seleccionar cualquier celda en cualquier lugar

También cuando arrastro mi pantalla hacia arriba y hacia abajo pierdo por marca de verificación

viewcontroller.swift

class ViewController: UIViewController, UITableViewDataSource { //class and subclass |) //---------------------------------------------------------------------------------------------------------------------------/ // Variable and constant, also IBAOutlet let section1 = ["this is used", "this is used to test", "this is used to test the lenght", "this is used to test the lenght of the text", "this is used to test the lenght of the text", "this is used to test the lenght of the text", "this is used to test the lenght of the text", "this is used to test the lenght of the text", "this is used to test the lenght of the text",] let section2 = ["this is used to test the lenght of the text"] let section3 = ["this is", "this is ",] @IBOutlet weak var scoreshow: UILabel! @IBOutlet weak var reset: UIButton! @IBOutlet weak var tableView: UITableView! // -------------------------------------------------------------------------------------- override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //---------------------------------------------------------------------------------------- // checkmarks when tapped func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let cell = tableView.cellForRowAtIndexPath(indexPath) { if cell.accessoryType == .Checkmark { cell.accessoryType = .None } else { cell.accessoryType = .Checkmark } } } //---------------------------------------------------------------------------------------- //number of sections for the table func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 5 } //---------------------------------------------------------------------------------------- //Calculate the amount of rows func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.section1.count; } //---------------------------------------------------------------------------------------- //Cells text label and config func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:"cell") cell.textLabel!.text = section1[indexPath.row] cell.textLabel!.numberOfLines = 0 return cell } //---------------------------------------------------------------------------------------- @IBAction func resetswitch(sender: UIButton) { } //---------------------------------------------------------------------------------------- }


Swift 4.0, todos juntos ahora:

import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var yourData = ["Cool","Sweet","Awesome"] var checked = [Bool]() override func viewDidLoad() { super.viewDidLoad() checked = Array(repeating: false, count: yourData.count) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchData.count } func tableView(_ tableView: UITableView, cellForRowAt IndexPath: IndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell //configure you cell here. if checked[IndexPath.row] == false{ cell.accessoryType = .none } else if checked[IndexPath.row] { cell.accessoryType = .checkmark } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if let cell = tableView.cellForRow(at: indexPath as IndexPath) { if cell.accessoryType == .checkmark { cell.accessoryType = .none checked[indexPath.row] = false } else { cell.accessoryType = .checkmark checked[indexPath.row] = true } } }

}


Un UITableView mantiene el estado seleccionado para selecciones simples o múltiples. Entonces IMO debería ser una muy buena razón para mantener un estado paralelo completo en alguna parte. Si solo desea cambiar la apariencia de la celda según el estado de selección, hágalo en la celda.

En su subclase UITableViewCell, anule setSelected así:

override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) self.accessoryType = selected ? .Checkmark : .None }

No es necesario usar ningún método delegado de vista de tabla.

Nota: debe llamar a super.setSelected; de lo contrario, la celda no mantiene el estado seleccionado correctamente.


Prueba esto:

var checked = [Bool]() // Have an array equal to the number of cells in your table func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell //configure you cell here. if !checked[indexPath.row] { cell.accessoryType = .None } else if checked[indexPath.row] { cell.accessoryType = .Checkmark } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let cell = tableView.cellForRowAtIndexPath(indexPath) { if cell.accessoryType == .Checkmark { cell.accessoryType = .None checked[indexPath.row] = false } else { cell.accessoryType = .Checkmark checked[indexPath.row] = true } } }

Para restablecer todas las casillas de verificación:

func resetChecks() { for i in 0.. < tableView.numberOfSections { for j in 0.. < tableView.numberOfRowsInSection(i) { if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: j, inSection: i)) { cell.accessoryType = .None } } } }


Swift 3.0

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let cell = tableView.cellForRow(at: indexPath) { cell.accessoryType = .checkmark } } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { if let cell = tableView.cellForRow(at: indexPath) { cell.accessoryType = .none } }


Swift 3.0
Usando solo una función para mantenerlo simple

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if let cell = tableView.cellForRow(at: indexPath as IndexPath) { if cell.accessoryType == .checkmark { cell.accessoryType = .none } else { cell.accessoryType = .checkmark } } }


Swift> 3.0

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { if let cell = tableView.cellForRow(at: indexPath) { cell.accessoryType = .none } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let cell = tableView.cellForRow(at: indexPath) { cell.accessoryType = .checkmark } }

Lo resolví usando dos funciones de Swift: didSelectRowAtIndexPath y didDeselectRowAtIndexPath.

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { if let cell = tableView.cellForRowAtIndexPath(indexPath) { cell.accessoryType = .None } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let cell = tableView.cellForRowAtIndexPath(indexPath) { cell.accessoryType = .Checkmark } }

Para que esto funcione correctamente, agregue una línea de código a su función cellForRowAtIndexPath para seleccionar una fila cuando la vista de tabla se dibuje en la pantalla; de lo contrario, no se invocará didDeselectRowAtIndexPath la primera vez que seleccione otra fila. Al igual que:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cellData", forIndexPath: indexPath) if (some condition to initially checkmark a row) cell.accessoryType = .Checkmark tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.Bottom) } else { cell.accessoryType = .None } return cell }