Custom Checkbox AccessoryView for UITableView - swift

I am using Custom AccessoryView for UITableViewCell. I am using a checkbox. Here, I want multiple selection. The code works fine while selection but while deselecting it I am having issues. I am not sure what I should be writing in cellForRowAtIndexPathMethod. The issue I am facing is, after deselecting the checkbox, I cannot select it again. Here is my code:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let fourthCell = tableView.dequeueReusableCellWithIdentifier("fourthCell", forIndexPath: indexPath) as! ItemDetailFourthTableViewCell
if indexPath != self.lastIndexPath {
fourthCell.accessoryView = UIImageView(image: UIImage(named: "checkBoxPassive.png"))
fourthCell.accessoryView?.tag = 2
}
if indexPath == self.lastIndexPath {
fourthCell.accessoryView = UIImageView(image: UIImage(named: "checkBoxActive.png"))
}
return fourthCell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
self.isSelected = true
self.lastIndexPath == indexPath
if indexPath.section == 1 {
let cell = tableView.cellForRowAtIndexPath(indexPath) as! ItemDetailFourthTableViewCell
print("The cell here is \(cell)")
print("Here the cell accessoryView is \(cell.accessoryView?.tag)")
if cell.accessoryView?.tag == 0 {
print("It is active")
cell.accessoryView = UIImageView(image: UIImage(named: "checkBoxPassive.png"))
} else if cell.accessoryView?.tag == 2 {
print("It is passive")
cell.accessoryView = UIImageView(image: UIImage(named: "checkBoxActive.png"))
}
}
}

Related

Issue while Expanding and Collapse of Table View Cell

i have a button and some content in a cell. Now when i tap a button i want the cell to expand and collapse, which is working fine for cell whose button is tapped. Now issue is coming that when i have expanded one cell and try to expand another cell while keeping first cell expanded it close first the previous cell and than expand my second cell. I want to expand and collapse the cells parallel and can collapse any cell rather than to collapse first. I'm changing height of cell on click of button. This is my code for expanding and collapsing,
extension ActiveConsultantDetailVC : UITableViewDelegate, UITableViewDataSource
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0
{
return 100
}
else if indexPath.row == 1
{
return 80
}
else if indexPath.row == 2
{
if (flag == true && indexPath.row == indexValue)
{
return UITableView.automaticDimension
}
else
{
return 40
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
else if indexPath.row == 2
{
let cell = consultantTableView.dequeueReusableCell(withIdentifier: "descriptionCell", for: indexPath) as! ConsultDescriptionTVC
indexDescription = indexPath
cell.expandBtn.addTarget(self, action: #selector(expandDescriptionView), for: .touchUpInside )
cell.selectionStyle = .none
return cell
}
}
#objc func expandDescriptionView()
{
let cell = consultantTableView.cellForRow(at: indexDescription) as! ConsultDescriptionTVC
indexValue = indexDescription.row
if flag && indexValue == indexDescription.row{
//statesDetailTableView.beginUpdates()
self.consultantTableView.reloadRows(at: [indexDescription], with: UITableView.RowAnimation.none)
// statesDetailTableView.endUpdates()
cell.expandBtn.setTitle("-", for: .normal)
flag = false
}
else{
//statesDetailTableView.beginUpdates()
self.consultantTableView.reloadRows(at: [indexDescription], with: UITableView.RowAnimation.none)
// statesDetailTableView.endUpdates()
cell.expandBtn.setTitle("+", for: .normal)
flag = true
}
}
As you can see when i tap it call a function that then expand height of cell. My UI Looks like this,
You just need to create 2 Cells in UITableView(In Storyboard). First cell for those who are not expandable and Second cell for the expandable.(In this case, now you don't need to change the Height of the CELL)
class TableVC: UITableViewController {
// MARK:- Constants And Vars
var isCellNAME1Expanded = false
var isCellNAME2Expanded = false
}
class TableVC: UITableViewDataSource, UITableViewDelegate {
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "simpleCell", for: indexPath) as! SideMenuBasicTableViewCell
switch indexPath.row {
case 0:
cell.itemName.text = "HOME"
break
case 1:
cell.itemName.text = "About Us"
break
case 2:
if(isCellNAME1Expanded){
//expandedCell
let cell = tableView.dequeueReusableCell(withIdentifier: "expandedCell", for: indexPath) as! SideMenuBasicTableViewCell
cell.itemName.text = "Expanded- CEll1"
return cell
}else{
cell.arrowDownImageView.isHidden = false
cell.itemName.text ="Expanded- CEll1"
}
break
case 3:
if(isCellNAME2Expanded){
//expandedCell
let cell = tableView.dequeueReusableCell(withIdentifier: "expandedCell", for: indexPath) as! SideMenuBasicTableViewCell
cell.itemName.text = "Expanded- CEll2"
return cell
}else{
cell.arrowDownImageView.isHidden = false
cell.itemName.text = "Expanded- CEll2"
}
break
case 4:
cell.itemName.text = "Portfolio"
break
case 5:
cell.itemName.text = "Contacts8"
break
default:
break
}
return cell
}
//And in `DidSelectRow` Method
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if(indexPath.row == 2){
if(isCellNAME1Expanded){
isCellNAME1Expanded = false
tableView.reloadRows(at: [indexPath], with: .none)
}else{
isCellNAME1Expanded = true
tableView.reloadRows(at: [indexPath], with: .none)
}
}if(indexPath.row == 3){
if(isCellNAME2Expanded){
isCellNAME2Expanded = false
tableView.reloadRows(at: [indexPath], with: .none)
}else{
isCellNAME2Expanded = true
tableView.reloadRows(at: [indexPath], with: .none)
}
}else if(indexPath.row == 0){
// Handle it yourself
}else if(indexPath.row == 1){
// Handle it yourself
}else if(indexPath.row == 4){
// Handle it yourself
}else if(indexPath.row == 5){
// Handle it yourself
}
}
}

Checkmark's associated with wrong row in TableView when using SearchBar

I am creating an application where when a User searches for an item in the TableView they can click on it and a checkmark appears next to it. However, say when I select the first item I have searched for and click it then delete my search the checkmark stays on the first row but for a completely different object, I searched for, to begin with (see images below).
When Searching
When not Searching
var searchingArray = [Symptoms]()
var filteredArray = [Symptoms]()
var selectedSymptoms = [Symptoms]()
var clicked = [String]()
var searchingUnderWay = false
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = searchingSymptomsTableView.dequeueReusableCell(withIdentifier: "ExtraSymptoms", for: indexPath) as? ExtraSymptomCell {
let searchingArrays: Symptoms!
if searchingUnderWay {
searchingArrays = self.filteredArray[indexPath.row]
} else {
searchingArrays = self.searchingArray[indexPath.row]
}
cell.updateUI(symptomNames: searchingArrays)
return cell
} else {
return UITableViewCell()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedRow: Symptoms!
let symptomName: String!
let cell : UITableViewCell = tableView.cellForRow(at: indexPath)!
if searchingUnderWay {
selectedRow = filteredArray[indexPath.row]
symptomName = filteredArray[indexPath.row].name as String
if clicked.contains(symptomName) {
cell.accessoryType = .none
let indexNumber = clicked.index(of: symptomName)
clicked.remove(at: indexNumber!)
if let element = selectedSymptoms.index(where: { $0.name == selectedRow.name }) {
selectedSymptoms.remove(at: element)
}
} else {
clicked.append(symptomName)
cell.accessoryType = .checkmark
searchingSymptomsTableView.reloadData()
selectedSymptoms.append(selectedRow)
}
} else {
selectedRow = searchingArray[indexPath.row]
symptomName = searchingArray[indexPath.row].name as String
if clicked.contains(symptomName) {
cell.accessoryType = .none
let indexNumber = clicked.index(of: symptomName)
clicked.remove(at: indexNumber!)
if let element = selectedSymptoms.index(where: { $0.name == selectedRow.name }) {
selectedSymptoms.remove(at: element)
}
} else {
clicked.append(symptomName)
cell.accessoryType = .checkmark
searchingSymptomsTableView.reloadData()
selectedSymptoms.append(selectedRow)
}
print(clicked)
print(selectedSymptoms)
}
}
I wish for the item I searched using the searchbar to still be checked when you delete the search.
Many thanks
Welcome to TableViewController logic. It seems really strange, but it works correct)
You need to override prepareForReuse() method in your ExtraSymptomCell. And clear all the values your cell contains including accessoryType
override func prepareForReuse() {
super.prepareForReuse()
accessoryType = .none
}
In your tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath):
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = searchingSymptomsTableView.dequeueReusableCell(withIdentifier: "ExtraSymptoms", for: indexPath) as? ExtraSymptomCell {
let symptomName: String!
let searchingArrays: Symptoms!
if searchingUnderWay {
searchingArrays = self.filteredArray[indexPath.row]
symptomName = filteredArray[indexPath.row].name as String
} else {
searchingArrays = self.searchingArray[indexPath.row]
symptomName = filteredArray[indexPath.row] as String
}
cell.updateUI(symptomNames: searchingArrays)
if clicked.contains(symptomName) {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
return cell
} else {
return UITableViewCell()
}
}
Since UITableViewCell are reused, the checkmark will appear in a cell when you reload Table Data.
In cellForRowAt set the accessoryType to .none, to remove a previously checked cell checkmark:
let cell : UITableViewCell = tableView.cellForRow(at: indexPath)!
cell.accessoryType = .none
This will remove the check from the previous search.

How to Set data to second tableview in same Class in swift

How to Set data to second tableview in same Class in swift.I am using two tables in the the same controller one for dropdown and another for listing. I am unable to set data to second table(listing) in class
as else part is not called in cellForRowAtIndexPath. Thanks in Advance
import UIKit
class PunchClockVC: UIViewController , UITableViewDataSource, UITableViewDelegate{
var appdel = UIApplication.sharedApplication().delegate as! AppDelegate
#IBOutlet weak var dropdownTable: UITableView!
#IBOutlet weak var mainTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.mainTable.registerClass(PunchClockCustomCell.self, forCellReuseIdentifier: "PunchClockCustomCell")
self.dropdownTable.registerClass(UITableViewCell.self, forCellReuseIdentifier: "dropdowncell")
self.dropdownTable.hidden = true
}
#IBAction func textFieldTapped(sender: AnyObject) {
if self.dropdownTable.hidden == true {
self.dropdownTable.hidden = false
}
else{
self.dropdownTable.hidden = false
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == dropdownTable {
return jobArrayID.count
}
return 8
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if tableView == self.dropdownTable {
let cell = tableView.dequeueReusableCellWithIdentifier("dropdowncell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = (jobArrayID[indexPath.row] as! String) + "-" + (jobArrayName[indexPath.row] as! String)
return cell
}
else {
let cell1 = tableView.dequeueReusableCellWithIdentifier("PunchClockCustomCell", forIndexPath: indexPath) as! PunchClockCustomCell
if indexPath.row == 0
{
cell1.jobcell?.font = UIFont(name: "MuseoSlab-500", size: 25.0)
cell1.locationcell?.font = UIFont(name: "MuseoSlab-500", size: 25.0)
cell1.timecell?.font = UIFont(name: "MuseoSlab-500", size: 25.0)
cell1.typecell?.font = UIFont(name: "MuseoSlab-500", size: 25.0)
cell1.jobcell?.textColor = UIColor.blackColor()
cell1.locationcell?.textColor = UIColor.blackColor()
cell1.timecell?.textColor = UIColor.blackColor()
cell1.typecell?.textColor = UIColor.blackColor()
cell1.jobcell?.text = "Job"
cell1.locationcell?.text = "Location"
cell1.timecell?.text = "Time"
cell1.typecell?.text = "Type"
// return cell1
}
else {
cell1.jobcell?.text = "Jobdata"
cell1.locationcell?.text = "Locationdata"
cell1.timecell?.text = "Timedata"
cell1.typecell?.text = "OUT"
// return cell1
}
return cell1
}
}
It's quite simple You need to set it only with cellForRowAtIndexPath method but the main thing to do is you need to code like below
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
if tableView == firstTbaleView
//outlet given to first tableView
{
let cell = tableView.dequeueReusableCellWithReuseIdentifier("cell1", forIndexPath: indexPath) as! cust1TableViewCell
cell.imgView.image = images[indexPath.row]
cell.filtLabel.text = self.filtersCount[indexPath.row]
return cell
}}else {
let cell2 = tableView.dequeueReusableCellWithReuseIdentifier("cell2", forIndexPath: indexPath) as! cust2TableViewCell
cell2.imgview.image = UIImage(named: colPhotos[indexPath.row])
cell2.labl.text = colNames[indexPath.row]
// cell2.layer.borderColor = UIColor.blueColor().CGColor
// cell2.layer.borderWidth = 2.0
return cell2
}
and that's it you can ask me for any help..
Lets make this a little safer:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.dropdownTable {
return jobArray.count
}
else if tableView == self.mainTable {
return = 5
}
//Default return 0. This way if references are broken or change, you won't crash
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if tableView == self.dropdownTable {
let cell = tableView.dequeueReusableCellWithIdentifier("dropdowncell", forIndexPath: indexPath) as! UITableViewCell
//configure your cell
return cell
}
else if tableView == self.mainTable {
let cell = tableView.dequeueReusableCellWithIdentifier("PunchClockCustomCell", forIndexPath: indexPath) as! PunchClockCustomCell
//configure your cell
return cell
}
//Shouln't ever reach here, but again, if we refactor somewhere then we'll see an error show up before here.
return UITableViewCell()
}

Swift: How to reload row height in UITableViewCell without reloading data

I have a case in which I have to reload only height of a UITableViewCell.
but if I call the function
tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: webView.tag, inSection: 0)], withRowAnimation: .Automatic)
it reloads the height as well as the data of the cell.
How can i just control the height of cell in Swift?
This is my cellForRow block :
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! CustomTableViewCell1
cell.heading.text = headerText
return cell
}
else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCellWithIdentifier("cell2", forIndexPath: indexPath) as! CustomTableViewCell2
ImageLoader.sharedLoader.imageForUrl(self.headerImage , completionHandler:{(image: UIImage?, url: String) in
cell.mainImage.image = image
})
return cell
}
else if indexPath.row == 2 {
let cell = tableView.dequeueReusableCellWithIdentifier("cell3", forIndexPath: indexPath) as! CustomTableViewCell3
//cell.aurthorImage.image = UIImage(named : "obama")
ImageLoader.sharedLoader.imageForUrl(self.headerImage , completionHandler:{(image: UIImage?, url: String) in
cell.aurthorImage.image = image
})
cell.aurthorImage.tag = aurthorID
cell.aurthorImage.layer.cornerRadius = cell.aurthorImage.frame.height/2
cell.aurthorImage.clipsToBounds = true
cell.aurthorImage.userInteractionEnabled = true
cell.aurthorImage.addGestureRecognizer(aurthorImageTapRecignizer)
cell.aurthorName.text = self.authorName
cell.time.text = self.time
self.followButton = cell.followButton
return cell
}
else if indexPath.row == 3 {
let cell = tableView.dequeueReusableCellWithIdentifier("cell4", forIndexPath: indexPath) as! CustomTableViewCell4
let htmlHeight = contentHeights[indexPath.row]
cell.webElement.tag = indexPath.row
cell.webElement.delegate = self
cell.webElement.loadHTMLString(HTMLContent, baseURL: nil)
cell.webElement.frame = CGRectMake(0, 0, cell.frame.size.width, htmlHeight)
return cell
}
else if indexPath.row == 4 {
let cell = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! CustomTableViewCell1
cell.heading.text = "Related Posts"
return cell
}
else if indexPath.row == 5{
let cell = tableView.dequeueReusableCellWithIdentifier("cell6", forIndexPath: indexPath) as! CustomTableViewCell6
return cell
}
else if indexPath.row == 6 {
let cell = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! CustomTableViewCell1
cell.heading.text = "Comments"
return cell
}
else if indexPath.row == 7 {
let cell = tableView.dequeueReusableCellWithIdentifier("cell5", forIndexPath: indexPath) as! CustomTableViewCell5
let htmlHeight = contentHeights[indexPath.row]
self.commentSection = cell.commentsView
self.commentSection.tag = indexPath.row
self.commentSection.delegate = self
let url = NSURL(string: commentsURL)
let requestObj = NSURLRequest(URL: url! )
self.commentSection.loadRequest(requestObj)
self.commentSection.frame = CGRectMake(0, 0, cell.frame.size.width, htmlHeight)
commentSectionDidNotLoad = false
return cell
}
else {
let cell = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! CustomTableViewCell1
cell.heading.text = headerText
return cell
}
You can use this code to update the cell's height without reloading their data:
tableView.beginUpdates()
tableView.endUpdates()
You can also use this method followed by the endUpdates method to animate the change in the row heights without reloading the cell.
UITableView Class Reference
start an update of the tableview and then end it without changing anything.
tableView.beginUpdates()
tableView.endUpdates()
This should make the tableview set the new height
You can regulate the height by either implementing the (a)heightForRowAtIndexPath with logic setting the heights or (b)with auto layout and automatic tableview row height
A.
override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
if [your condition, row == 5 in your comment] {
return 100
} else {
return 40
}
}
Whenever you want to change the height you would just call these two rows
tableView.beginUpdates()
tableView.endUpdates()
B.
in viewDidLoad
tableView.estimatedRowHeight = 40.0
tableView.rowHeight = UITableViewAutomaticDimension
and then you can just expose the layout constraint that set's the cells height and access it to set the height when you want
cell.heightConstraint.constant = 100
tableView.beginUpdates()
tableView.endUpdates()
About your question for example, to give a specific height dimension :
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 3 {
return 50.0
}
return 72.0
}
But I think you have a webView inside a cell so, generally, to calculate the dynamic height of a UITableViewCell with a UIWebView:
(this example have two webViews)
class MyTableViewController: UITableViewController, UIWebViewDelegate
{
var content : [String] = ["<!DOCTYPE html><html><head><title>Page Title</title></head><body><h1>My First Heading</h1><p>My first paragraph</p></body></html>", "<HTML><HEAD><TITLE>Coca-Cola</TITLE></HEAD><BODY>In Chinese, Coca-Cola means Bite the Wax Tadpole</BODY></HTML>"]
var contentHeights : [CGFloat] = [0.0, 0.0]
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("myCustomCell", forIndexPath: indexPath) as! MyCustomCell
let htmlString = content[indexPath.row]
let htmlHeight = contentHeights[indexPath.row]
cell.webView.tag = indexPath.row
cell.webView.delegate = self
cell.webView.loadHTMLString(htmlString, baseURL: nil)
cell.webView.frame = CGRectMake(0, 0, cell.frame.size.width, htmlHeight)
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
return contentHeights[indexPath.row]
}
func webViewDidFinishLoad(webView: UIWebView)
{
if (contentHeights[webView.tag] != 0.0)
{
// height knowed, no need to reload cell
return
}
contentHeights[webView.tag] = webView.scrollView.contentSize.height
tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: webView.tag, inSection: 0)], withRowAnimation: .Automatic)
}
}
You can use the view height constraint in the cell, by updating the view in cell height you can update the specific cell height.
let height = cell.Height_constraint.constant
cell.Height_constraint.constant = height + 200 //200 you can use any number
Height_constraint: is the height constraint of subView in my cell.

Set UITableView rows as selected if contained in an array

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)")
}
}