I have an application where I have two sections the issue I have now is if I select an item in section 1, it automatically selects a cell in section 2 which is not suppose to be. I want Items to be selectable in section 1 without affecting section two.
below is my selection
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.section {
case 0:
showCustomDialog(subD: sub[indexPath.row])
case 1:
let cell = tableView.cellForRow(at: indexPath) as! VasListCell
cell.checkBox.setOn(true, animated: true)
default: break
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
switch indexPath.section {
case 1:
let cell = tableView.cellForRow(at: indexPath) as! VasListCell
cell.checkBox.setOn(false, animated: true)
default: break
}
}
where I am using the selected index
func selectedIndex(viewcontroller: UIViewController) {
let selectedRows = tableView.indexPathsForSelectedRows
guard let vasRow = selectedRows?.map ({ vas[$0.row] }) else { return }
selectedVasData = vasRow
let vasData = selectedVasData
let subData = selectedSubData
let vcr = viewcontroller as! CheckoutVC
vcr.vas = vasData
vcr.sub = subData
let tot1 = subData.compactMap {$0.price}
let tot2 = vasData.compactMap {$0.amount}
let tot = tot1 + tot2
let reduced = tot.compactMap(Double.init).reduce(0, +)
vcr.tableView.reloadData()
self.present(viewcontroller, animated: true, completion: nil)
print("CELL INDEX vas \(StaticFunc.convertDoubleToCurrency(amount: reduced))")
}
Related
I'm setting up survey screen consists of table view so that each cell has table view of checkboxes the problem is that when I check box and scroll down I find that another cell dequeued with checkbox selected.
I have tried to change selection state in prepare for reuse but didn't work
this code for checkbox table view
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = taskActionOptionTableView.dequeueReusableCell(withIdentifier: Constants.TASK_CHOOSE_OPTIONCELL_ID, for: indexPath) as? TaskChooseOptionCell
if taskResponseActionId == nil {
taskResponseAction = TaskResponseAction()
}
cell?.taskCheckBox.boxType = .circle
cell?.taskCheckBox.markType = .radio
cell?.taskCheckBox.boxLineWidth = 2
cell?.delegate = self
if cell?.taskCheckBox.checkState == .checked {
print("checked")
}
if taskAction?.taskDependentActions.count != 0 {
cell?.scoreOperator = taskAction?.taskDependentActions[indexPath.section].scoreOperator
cell?.scoreNumberValue = taskAction?.taskDependentActions[indexPath.section].scoreNumberValue
}
cell?.taskActionOptionScoreValue = taskAction?.taskActionOptions[indexPath.row].taskActionOptionScoreValue
if cell == nil {
cell = TaskChooseOptionCell.customCell
}
if isDependent {
cell?.taskDepActionOption = taskDependentActionOptions?[indexPath.row]
return cell!
} else {
cell?.taskActionOption = taskActionOptions?[indexPath.row]
return cell!
}
}
And this for the main table view cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let id = task?.taskActions[indexPath.section].actionTypeId
let cellType = TaskActionType.allCases.filter {
return $0.id == id
}.first
guard let cellDescType = cellType else { return UITableViewCell() }
switch cellDescType {
case .date:
let dateCell = tableView.dequeueReusableCell(withIdentifier: Constants.DATE_CELL_ID, for: indexPath) as! DateCell
dateCell.taskMaterial = taskActionsOnMaterialArray[indexPath.row].material
return dateCell
case .multiChoice:
let multiChoiceCell = tableView.dequeueReusableCell(withIdentifier: Constants.MULTI_CHOOSE_CELL_ID, for: indexPath) as! MultiChooseCell
multiChoiceCell.delegate = self
multiChoiceCell.taskMaterial = task?.taskRestrictedMaterials[indexPath.row]
multiChoiceCell.taskAction = task?.taskActions[indexPath.section]
multiChoiceCell.taskActionOptions = Array((task?.taskActions[indexPath.section].taskActionOptions)!)
return multiChoiceCell
case .text:
let textCell = tableView.dequeueReusableCell(withIdentifier: Constants.TEXT_CELL_ID, for: indexPath) as! TextViewCell
return textCell
case .singleChoice:
let singleChoiceCell = tableView.dequeueReusableCell(withIdentifier: Constants.SINGLE_CHOICE_CELL_ID, for: indexPath) as! SingleChoiceCell
singleChoiceCell.delegate = self
singleChoiceCell.taskMaterial = task?.taskRestrictedMaterials[indexPath.row]
singleChoiceCell.taskAction = task?.taskActions[indexPath.section]
singleChoiceCell.taskActionOptions = Array((task?.taskActions[indexPath.section].taskActionOptions)!)
return singleChoiceCell
case .number:
let numberCell = tableView.dequeueReusableCell(withIdentifier: Constants.NUMBER_CELL_ID, for: indexPath) as! NumberCell
return numberCell
}
}
In your data model you can add a variable like var done : Bool = " " and set it to false initially and toggle it on didSelectRow to true or false accordingly and check this variable on the time of setting accessoryType. If its true then set it to .checked else set it to .none.
I have a tableview with 3 collapsible sections. users can only select rows in section 3 and when they select it goes green. However, when this section is collapsed all the selections are forgotten and when I re-open the section, usually the first row is always green (though it shouldn't be). Sometimes, other sections end up being green too when they shouldn't - not sure what I've got wrong?
// Number of table sections
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
// Set the number of rows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.expandedSectionHeaderNumber == section) {
// If markscheme, create the markscheme format
if (section == 2)
{
return self.markschemeRows.count
}
else
{
let arrayOfItems = self.sectionItems[section] as! NSArray
return arrayOfItems.count
}
} else {
return 0;
}
}
// Set titles for sections
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if (self.sectionNames.count != 0) {
return self.sectionNames[section] as? String
}
return ""
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44.0;
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
return 0;
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
//recast your view as a UITableViewHeaderFooterView
let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.contentView.backgroundColor = UIColor.darkGray
header.textLabel?.textColor = UIColor.white
if let viewWithTag = self.view.viewWithTag(kHeaderSectionTag + section) {
viewWithTag.removeFromSuperview()
}
let headerFrame = self.view.frame.size
let theImageView = UIImageView(frame: CGRect(x: headerFrame.width - 32, y: 13, width: 18, height: 18));
theImageView.image = UIImage(named: "Chevron-Dn-Wht")
theImageView.tag = kHeaderSectionTag + section
header.addSubview(theImageView)
// make headers touchable
header.tag = section
let headerTapGesture = UITapGestureRecognizer()
headerTapGesture.addTarget(self, action: #selector(CaseViewController.sectionHeaderWasTouched(_:)))
header.addGestureRecognizer(headerTapGesture)
}
// Load the table data
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
let section = self.sectionItems[indexPath.section] as! NSArray
cell.textLabel?.textColor = UIColor.black
cell.selectionStyle = .none
//cell.backgroundColor = .white
// Get the data from different arrays depending on the section
if indexPath.section == 2 {
cell.textData?.text = markschemeRows[indexPath.row]
} else {
cell.textData?.text = section[indexPath.row] as! String
}
return cell
}
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if indexPath.section == 0{
if indexPath.row == 0{
return nil
}
}
else if indexPath.section == 1{
if indexPath.row == 0{
return nil
}
}
return indexPath
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
let cell = tableView.cellForRow(at: indexPath)
cell?.backgroundColor = .green
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let cell = tableView.cellForRow(at: indexPath)
if (cell?.backgroundColor == .green)
{
cell?.backgroundColor = .white
}
}
// MARK: - Expand / Collapse Methods
#objc func sectionHeaderWasTouched(_ sender: UITapGestureRecognizer) {
let headerView = sender.view as! UITableViewHeaderFooterView
let section = headerView.tag
let eImageView = headerView.viewWithTag(kHeaderSectionTag + section) as? UIImageView
if (self.expandedSectionHeaderNumber == -1) {
self.expandedSectionHeaderNumber = section
tableViewExpandSection(section, imageView: eImageView!)
} else {
if (self.expandedSectionHeaderNumber == section) {
tableViewCollapeSection(section, imageView: eImageView!)
} else {
let cImageView = self.view.viewWithTag(kHeaderSectionTag + self.expandedSectionHeaderNumber) as? UIImageView
tableViewCollapeSection(self.expandedSectionHeaderNumber, imageView: cImageView!)
tableViewExpandSection(section, imageView: eImageView!)
}
}
}
func tableViewCollapeSection(_ section: Int, imageView: UIImageView) {
let sectionData = self.sectionItems[section] as! NSArray
self.expandedSectionHeaderNumber = -1;
if (sectionData.count == 0) {
return;
} else {
UIView.animate(withDuration: 0.4, animations: {
imageView.transform = CGAffineTransform(rotationAngle: (0.0 * CGFloat(Double.pi)) / 180.0)
})
var indexesPath = [IndexPath]()
// If markscheme, different number needed
if (section == 2)
{
for i in 0 ..< markschemeRows.count {
let index = IndexPath(row: i, section: section)
indexesPath.append(index)
}
}
else
{
for i in 0 ..< sectionData.count {
let index = IndexPath(row: i, section: section)
indexesPath.append(index)
}
}
self.tableView!.beginUpdates()
self.tableView!.deleteRows(at: indexesPath, with: UITableView.RowAnimation.fade)
self.tableView!.endUpdates()
}
}
func tableViewExpandSection(_ section: Int, imageView: UIImageView) {
let sectionData = self.sectionItems[section] as! NSArray
if (sectionData.count == 0) {
self.expandedSectionHeaderNumber = -1;
return;
} else {
UIView.animate(withDuration: 0.4, animations: {
imageView.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat(Double.pi)) / 180.0)
})
var indexesPath = [IndexPath]()
// If markscheme, create the markscheme format
if (section == 2)
{
for i in 0 ..< markschemeRows.count {
let index = IndexPath(row: i, section: section)
indexesPath.append(index)
}
}
else
{
for i in 0 ..< sectionData.count {
let index = IndexPath(row: i, section: section)
indexesPath.append(index)
}
}
self.expandedSectionHeaderNumber = section
self.tableView!.beginUpdates()
self.tableView!.insertRows(at: indexesPath, with: UITableView.RowAnimation.fade)
self.tableView!.endUpdates()
}
}
The key thing to understand here is that the Cells are Reused when you say
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
dequeueReusableCell basically reuses a previously loaded UITableViewCell and in your case you changed the background color of the cell to green
To get a better understanding of the concept consider reading some articles like this one on Reusing Cells
Changes in Code
What you should do considering the above in mind
var backgroundColors = [UIColor](repeating: UIColor.white, count: 10)
you have to save the state of the colors in a model (ideally you should make a custom struct)
now in cellForRowAt add this
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
.
.
cell.backgroundColor = backgroundColors[indexPath.row]
// **EDIT**
let cellShouldBeSelected = backgroundColors[indexPath.row] == .green
if cellShouldBeSelected {
tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
}
.
.
return cell
}
And your didSelectRowAt and didDeselectRowAt should update the model
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.backgroundColors[indexPath.row] = .green
tableView.reloadRows(at: [indexPath], with: .none)
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if (self.backgroundColors[indexPath.row] == .green) {
self.backgroundColors[indexPath.row] = .white
tableView.reloadRows(at: [indexPath], with: .none)
}
}
On second thought
Solution 2 (Recommended)
From you comments, i see you only need one selected cell at one time, assuming that keeping an array of backgroundColors is just a bad idea.
declare a int for the selected index
// -1 representing nothing is selected in the beginning
var selectedRow = -1
now your cellForRowAt will look like
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
.
.
if indexPath.section == 2, indexPath.row == self.selectedRow {
cell.backgroundColor = .green
} else {
cell.backgroundColor = .white
}
.
.
return cell
}
And your didSelectRowAt
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 2 {
self.selectedRow = indexPath.row
tableView.reloadSections([2], with: .automatic)
}
}
And now you can remove didDeselectRowAt completely
I would like that users can choose maximum one voice. And that the checkmark jumps to where you tapt and deselect the other.
It looks like very simple, but I don't see the solution. And I can't find the answer on the internet.
Please can anybody help me?
Thanks advance!
import UIKit
import AVFoundation
class voicesTableViewController: UITableViewController {
fileprivate let synthesizer = AVSpeechSynthesizer()
fileprivate var speechVoices = AVSpeechSynthesisVoice.speechVoices()
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return speechVoices.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
//Name
let voice = speechVoices[indexPath.row]
let voiceLang = voice.language as? String
let theVoice = UserDefaults.standard.object(forKey:"voice") as? String
cell.textLabel?.text = voice.name
// Language
if let language = countryName(countryCode: voice.language) {
cell.detailTextLabel?.text = "\(language)"
}
else {
cell.detailTextLabel?.text = ""
}
cell.detailTextLabel?.textColor = UIColor.gray
// Checkmark
if (theVoice != nil) {
if(theVoice == voiceLang) {
cell.accessoryType = UITableViewCellAccessoryType.checkmark
}
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let voice = speechVoices[indexPath.row]
if tableView.cellForRow(at: indexPath)?.accessoryType == UITableViewCellAccessoryType.checkmark {
tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.none
}
else
{
//if ((tableView.indexPathsForSelectedRows?.count)! > 1) {
tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.checkmark
//}
}
UserDefaults.standard.set(voice.language, forKey:"voice")
UserDefaults.standard.synchronize()
tableView.deselectRow(at: indexPath, animated: true)
}
func countryName(countryCode: String) -> String? {
let preferredLanguage = NSLocale.preferredLanguages[0] as String
let current = Locale(identifier: preferredLanguage)
return current.localizedString(forLanguageCode: countryCode) ?? nil
//return current.localizedString(forIdentifier: indentifier) ? nil
}
}
Simple change of function cellForRow:atIndexPathshould work:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
//Name
let voice = speechVoices[indexPath.row]
let voiceLang = voice.language as? String
let theVoice = UserDefaults.standard.object(forKey:"voice") as? String
cell.textLabel?.text = voice.name
// Language
if let language = countryName(countryCode: voice.language) {
cell.detailTextLabel?.text = "\(language)"
}
else {
cell.detailTextLabel?.text = ""
}
cell.detailTextLabel?.textColor = UIColor.gray
// Checkmark
if(theVoice != nil && theVoice == voiceLang) {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
return cell
}
UPD#1
But you can use better solution:
1) Add property fileprivate var selectedIndexPath: IndexPath?
2) Change function func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)to next one:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
//Name
let voice = speechVoices[indexPath.row]
let voiceLang = voice.language as? String
let theVoice = UserDefaults.standard.object(forKey:"voice") as? String
cell.textLabel?.text = voice.name
// Language
if let language = countryName(countryCode: voice.language) {
cell.detailTextLabel?.text = "\(language)"
}
else {
cell.detailTextLabel?.text = ""
}
cell.detailTextLabel?.textColor = UIColor.gray
// Checkmark
cell.accessoryType = self.selectedIndexPath == indexPath ? .checkmark : .none
return cell
}
3) And then in func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) you can do next:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let voice = speechVoices[indexPath.row]
self.selectedIndexPath = indexPath
UserDefaults.standard.set(voice.language, forKey:"voice")
UserDefaults.standard.synchronize()
tableView.deselectRow(at: indexPath, animated: true)
tableView.reloadRows(at: [indexPath], with: .automatic)
}
i need to change my image in cell using view will appear. But i can't use my cell in view will appear here what i've done
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
let cell: HomeCellTableViewCell = self.tableCity.dequeueReusableCell(withIdentifier: "Cell") as! HomeCellTableViewCell
if session == nil {
print("first")
cell.iconForDownload.setImage(UIImage(named: "ic_download"), for: .normal)
} else {
print("second")
cell.iconForDownload.setImage(UIImage(named: "ic_next_green"), for: .normal)
}
}
it print "first" but the image still didn't change
in my cellForRowAt :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: HomeCellTableViewCell = self.tableCity.dequeueReusableCell(withIdentifier: "Cell") as! HomeCellTableViewCell
let city = listData[indexPath.row]
cell.labelNameCity.text = city.region
cell.labelNameCityJpn.text = city.regionJpn
let stringImage = config.BASE_URL+city.imgArea
let url = URL(string: stringImage.replacingOccurrences(of: " ", with: "%20"))
urlDownload = config.BASE_URL+kota.urlDownload
urlDownloadFinal = URL(string: urlDownload.replacingOccurrences(of: " ", with: "%20"))
if session == nil {
cell.imageCity.kf.setImage(with: url)
cell.iconForDownload.setImage(UIImage(named: "ic_download"), for: .normal)
} else {
cell.imageCity.kf.setImage(with: url)
cell.iconForDownload.setImage(UIImage(named: "ic_next_green"), for: .normal)
}
return cell
}
You need to use cellForRow(at:) to get the cell it will return optional UITableViewCell so use if let or guard let to wrapped the optional.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
let indexPath = IndexPath(row: 0, section: 0) //Set your row and section
if let cell = tableView.cellForRow(at: indexPath) as? HomeCellTableViewCell {
//access cell
}
}
Note: The batter approach is to set your datasource array and simply reload the affected table rows using reloadRows(at:with:).
let indexPath = IndexPath(row: 0, section: 0) //Set your row and section
self.tableView.reloadRows(at: [indexPath], with: .automatic)
I have data stored in a realm database. I retrieve the information from the database and place it in an array. I then search through the array and set the cell to selected if it is contained in the array.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:SubjectsTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! SubjectsTableViewCell
var subject: Subjects!
subject = Subjects[Int(indexPath.row)]
cell.subject.text = subject.subjectTitle
if chosenSubjects.contains(subject.subjectTitle) {
cell.selected = true
cell.accessoryType = .Checkmark
tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.None)
cell.highlighted = true
} else {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
}
return cell
}
Unfortunately, the above code is giving me some strange results. Sometimes the cells are highlighted and display a checkmark, sometimes the first cell in the table is unhighlighted, but displays a checkmark. Sometimes I have to press the cell twice to deselect. Note, I have also set the didSelectRowAtIndexPath and didDeselectRowAtIndexPath as follows:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Get the row data for the selected row
self.tableView.allowsMultipleSelection = true
let cell:SubjectsTableViewCell = tableView.cellForRowAtIndexPath(indexPath) as! SubjectsTableViewCell
cell.accessoryType = .Checkmark
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
// Get the row data for the selected row
self.tableView.allowsMultipleSelection = true
let cell:SubjectsTableViewCell = tableView.cellForRowAtIndexPath(indexPath) as! SubjectsTableViewCell
cell.accessoryType = .None
}
I believe that this can occur because you are reusing cells with your line
let cell:SubjectsTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! SubjectsTableViewCell
Instead, try doing something like this:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:SubjectsTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! SubjectsTableViewCell
var subject: Subjects!
subject = Subjects[Int(indexPath.row)]
cell.subject.text = subject.subjectTitle
if chosenSubjects.contains(subject.subjectTitle) {
cell.selected = true
cell.accessoryType = .Checkmark
tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.None)
cell.highlighted = true
} else {
cell.selected = false
cell.accessoryType = .None
cell.highlighted = false
tableView.deselectRowAtIndexPath(indexPath, animated: false)
}
return cell
}
Hope this helps; let me know if it doesn't!
Edit:
I just noticed that within your select and deselect tableview functions, you don't actually update your chosenSubjects array for the given row. You need to update this before you call cellForRowAtIndexPath; otherwise, the if condition (in your cellForRowAtIndexPath) will fail - thus leading to the weird behaviour!
Try this:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Get the row data for the selected row
self.tableView.allowsMultipleSelection = true
var subject: Subjects! = Subjects[Int(indexPath.row)]
chosenSubjects.addObject(subject.subjectTitle)
let cell:SubjectsTableViewCell = tableView.cellForRowAtIndexPath(indexPath) as! SubjectsTableViewCell
cell.accessoryType = .Checkmark
}
and this:
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
// Get the row data for the selected row
self.tableView.allowsMultipleSelection = true
var subject: Subjects! = Subjects[Int(indexPath.row)]
chosenSubjects = chosenSubjects.filter() { $0 != subject.subjectTitle }
let cell:SubjectsTableViewCell = tableView.cellForRowAtIndexPath(indexPath) as! SubjectsTableViewCell
cell.accessoryType = .None
}
var userCLient = string is an empty string array declare..
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedRow:UITableViewCell = tableView.cellForRow(at: indexPath)!
if selectedRow.accessoryType == UITableViewCellAccessoryType.none{
selectedRow.accessoryType = UITableViewCellAccessoryType.checkmark
selectedRow.tintColor = UIColor.green
var dict = arrRes[(indexPath as NSIndexPath).row]
let EmpID = dict["user_id"] as? Int
self.userCLient.append(String(describing: EmpID!))
print("Employee:\(self.userCLient)")
}
else{
selectedRow.accessoryType = UITableViewCellAccessoryType.none
var dict = arrRes[(indexPath as NSIndexPath).row]
let EmpID = dict["user_id"] as? Int
if let index = self.userCLient.index(of: String(describing: EmpID!)) {
self.userCLient.remove(at: index)
}
print("Employee:\(self.userCLient)")
}
}