swift update cell accessory type - ios

I am trying to update my table cell accessory type when I tap a cell.
here is the code:
var selectedCellArray :[FriendTableViewCell] = []
var friends: [PFUser] = []
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var selectedCell = self.tableView(tableView, cellForRowAtIndexPath: indexPath) as FriendTableViewCell
if (selectedCell.accessoryType == UITableViewCellAccessoryType.None){
selectedCell.accessoryType = .Checkmark
selectedCellArray.append(selectedCell)
}else if (selectedCell.accessoryType == UITableViewCellAccessoryType.Checkmark){
selectedCell.accessoryType = .None
var index = 0
for cell in selectedCellArray{
if (cell != selectedCell){
index++
}else{
break
}
}
selectedCellArray.removeAtIndex(index)
}
self.tableView(tableView, cellForRowAtIndexPath: indexPath)
}
and
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("friend") as? FriendTableViewCell ?? FriendTableViewCell()
var round = 0
var friend: AnyObject = self.friends[indexPath.row]
cell.firstNameLabel.text = friend["firstName"] as? String
cell.lastNameLabel.text = friend["lastName"] as? String
println(selectedCellArray)
round++
var hasFound = false
if (self.checkSelectedArray(selectedCellArray, target: cell)){
cell.accessoryType = .Checkmark
}else{
cell.accessoryType = .None
}
cell.firstNameLabel.sizeToFit()
cell.lastNameLabel.sizeToFit()
return cell
}
func checkSelectedArray(selectedArray:[FriendTableViewCell], target:FriendTableViewCell) -> Bool{
for cell in selectedCellArray{
if cell.isEqual(target){
return true
}
}
return false
}
Also, is there a built-in method like array.contain? Currently, I wrote a function by myself to check if an array has certain element......
Please help me out... I am stuck for this problem for about 8 hours

Storing the reference to the cell isn't a valid strategy as cells can be re-used when the table scrolls. You can't use the current cell accessory to indicate selection state for the same reason.
You can use an NSIndexSet or a Swift dictionary. Here is an implementation using a dictionary -
var selectedCells :Dictionary<String,PFUser>()
var friends: [PFUser] = []
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedCell = tableView.cellForRowAtIndexPath(indexPath) as FriendTableViewCell
let objectId=friends[indexPath.row].objectId
if (selectedCells[objectId] != nil){
selectedCell.accessoryType = .None
selectedCells.removeValueForKey(objectId)
} else
selectedCell.accessoryType = .Checkmark
selectedCells[objectId]=friends[indexPath.row]
}
tableView.deselectRowAtIndexPath(indexPath, animated:false)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("friend") as? FriendTableViewCell ?? FriendTableViewCell()
var round = 0
var friend: AnyObject = self.friends[indexPath.row]
cell.firstNameLabel.text = friend["firstName"] as? String
cell.lastNameLabel.text = friend["lastName"] as? String
if (selectedCells[friend.objectId] != nil){
selectedCell.accessoryType = .Checkmark
} else
selectedCell.accessoryType = .None
}
cell.firstNameLabel.sizeToFit()
cell.lastNameLabel.sizeToFit()
return cell
}

Related

Single and MultiSelection cells in same tableView | Swift

Before duplicating this question, please be known that I've spent days on this issue, working hours, and looking for all same sort of questions on SO, but there is something I am missing or doing wrong.
I have a tableView in which the data is being populated via API response. Below is the model I have.
struct Model : Codable {
let bugClassification : [Bug]?
}
struct Bug : Codable {
let selectable : String? //Telling wether cell is single/Multi selected
var options : [Options]?
}
struct Options : Codable, Equatable {
let title : String?
let id: Int
var isCellSelected: Bool = false
}
Scenario
I want to create multiple sections, each having different cell depending upon the type of selectable, either single or multi. I have achieved that, but the problem I am getting is that whenever I scroll, random cells are also selected. Now, I know this behaviour is because of tableView reusing the cells. But I am confused as how to handle all this. Also, I want to put the validation on the sections, that is, every section should have atleast one cell selected. Kindly guide me in the right direction, and any small help would be appreciated. Below is my code.
CellForRowAt
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if bugClassification[indexPath.section].selectable?.lowercased() == "multi-select" {
//Multi-Selection
let cell = tableView.dequeueReusableCell(withIdentifier: multiSelectionCellID) as! MultiSelectionCell
let item = bugClassification[indexPath.section].options![indexPath.row]
cell.label.text = item.title
if item.isCellSelected {
cell.checkMarkImageView.alpha = 1
cell.checkMarkView.layer.borderColor = UIColor.white.cgColor
cell.checkMarkView.backgroundColor = .emerald
} else if item.isCellSelected {
cell.checkMarkImageView.alpha = 0
cell.checkMarkView.layer.borderColor = UIColor.veryLightBlue.cgColor
cell.checkMarkView.backgroundColor = .white
}
return cell
} else {
//Single-Selection
let cell = tableView.dequeueReusableCell(withIdentifier: singleSelectionCellID) as! SingleSelectionCell
let item = bugClassification[indexPath.section].options![indexPath.row]
cell.label.text = item.title
if item.isCellSelected {
cell.checkMarkImageView.alpha = 1
cell.checkMarkView.layer.borderColor = UIColor.emerald.cgColor
} else {
cell.checkMarkImageView.alpha = 0
cell.checkMarkView.layer.borderColor = UIColor.veryLightBlue.cgColor
}
return cell
}
}
DidSelectRow Method
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if bugClassification[indexPath.section].selectable?.lowercased() == "multi-select" {
var item = bugClassification[indexPath.section].options![indexPath.row]
item.isCellSelected = !item.isCellSelected
bugClassification[indexPath.section].options![indexPath.row] = item
self.tableView.reloadRows(at: [indexPath], with: .automatic)
} else {
let items = bugClassification[indexPath.section].options
if let selectedItemIndex = items!.indices.first(where: { items![$0].isCellSelected }) {
bugClassification[indexPath.section].options![selectedItemIndex].isCellSelected = false
if selectedItemIndex != indexPath.row {
bugClassification[indexPath.section].options![indexPath.row].isCellSelected = true
}
} else {
bugClassification[indexPath.section].options![indexPath.row].isCellSelected = true
}
self.tableView.reloadSections([indexPath.section], with: .automatic)
}
}
In cellForRowAt
if item.isCellSelected == true{
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
and update the model by every selection
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let item = bugClassification[indexPath.section].options![indexPath.row]
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .none
if indexPath.section == 0{
item.isCellSelected.isSelected = false
}else{
item.isCellSelected.isSelected = false
}
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = bugClassification[indexPath.section].options![indexPath.row]
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .checkmark
if indexPath.section == 0{
item.isCellSelected.isSelected = true
}else{
item.isCellSelected.isSelected = true
}
}
}

Swift 5 UITableViewCell : Expand one section and collapse the expanded section

I have implemented the following code to add expand/collapse feature to UITableView sections. When user click each section1, it expands and when we click the same section1 it collapses. But, I want the section1 to collapse, if I am expanding section2. How can I implement this feature to my code added below.
struct FaqData{
var faqHead = String()
var faqImage = String()
var questionArray : [(question : String, answer : String, answerurl : String)] = [(String,String,String)]()
var openSection = Bool()
}
var supportArray = [FaqData]()
func numberOfSections(in tableView: UITableView) -> Int {
return supportArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0{
return 1
}
else{
if supportArray[section].openSection == true{
return supportArray[section].questionArray.count + 1
}else{
return 1
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
if indexPath.section == 0{
let cell = tableView.dequeueReusableCell(withIdentifier: "SupportCenterID", for: indexPath) as! SupportCenterTableViewCell
cell.selectionStyle = UITableViewCell.SelectionStyle.none
cell.faqCollection.reloadData()
return cell
}
else{
if indexPath.row == 0{
let cell = tableView.dequeueReusableCell(withIdentifier: "SupportFaqID") as! SupportCenterFaqTableViewCell
cell.selectionStyle = UITableViewCell.SelectionStyle.none
let faqHead = supportArray[indexPath.section].faqHead
cell.imageText.text = faqHead.capitalized
cell.imageButton.setImage(UIImage(named: supportArray[indexPath.section].faqImage), for: .normal)
return cell
}
else{
let cell = tableView.dequeueReusableCell(withIdentifier: "QuestionID") as! SupportQuestionTableViewCell
cell.selectionStyle = UITableViewCell.SelectionStyle.none
cell.isSelected = true
cell.questionLabel.text = "Q.\(indexPath.row) " + supportArray[indexPath.section].questionArray[indexPath.row - 1].question
cell.answerLabel.text = supportArray[indexPath.section].questionArray[indexPath.row - 1].answer
print(supportArray[indexPath.section].questionArray[indexPath.row - 1].answerurl)
if supportArray[indexPath.section].questionArray[indexPath.row - 1].answerurl == ""{
cell.urlButton.isHidden = true
}
else{
cell.urlButton.isHidden = false
}
cell.urlButton.isHidden = true
cell.urlButton.tag = indexPath.row
UserDefaults.standard.set(indexPath.section, forKey: "SectionValue")
cell.urlButton.addTarget(self, action: #selector(urlButtonClicked(_:)), for: .touchUpInside)
cell.layoutMargins = UIEdgeInsets.zero
return cell
}
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if supportArray[indexPath.section].openSection == true{
if indexPath.section != 0{
if indexPath.row == 0{
let cell = tableView.cellForRow(at: indexPath) as! SupportCenterFaqTableViewCell
cell.faqView.backgroundColor = .white
cell.imageButton.tintColor = UIColor(hexString: "#D71B61")
cell.imageText.textColor = UIColor(hexString: "#D71B61")
}
}
supportArray[indexPath.section].openSection = false
let sections = IndexSet.init(integer: indexPath.section)
tableView.reloadSections(sections, with: .fade)
}
else{
supportArray[indexPath.section].openSection = true
let sections = IndexSet.init(integer: indexPath.section)
tableView.reloadSections(sections, with: .fade)
if indexPath.section != 0{
if indexPath.row == 0{
let cell = tableView.cellForRow(at: indexPath) as! SupportCenterFaqTableViewCell
cell.faqView.backgroundColor = UIColor(hexString: "#D71B61")
cell.imageButton.tintColor = .white
cell.imageText.textColor = .white
}
}
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
Can anyone provide a solution for this?
do this in didselecterow method. This is the else case of your condition
// You will need to reload multiple sections. So make an array.
var reloadSections = [Int]()
// find already opened array
if let alreadyOpenSection = supportArray.firstIndex(where: { (faq) -> Bool in
return faq.openSection
}) {
// if found, toggle the openSections bit
supportArray[alreadyOpenSection].openSection = false
// add it to reload sections array
reloadSections.append(alreadyOpenSection)
}
supportArray[indexPath.section].openSection = true
reloadSections.append(indexPath.section)
// create index set with reload sections array
let sections = IndexSet.init(reloadSections)
tableView.reloadSections(sections, with: .fade)
// below code is same
if indexPath.section != 0{
if indexPath.row == 0{
let cell = tableView.cellForRow(at: indexPath) as! SupportCenterFaqTableViewCell
cell.faqView.backgroundColor = UIColor(hexString: "#D71B61")
cell.imageButton.tintColor = .white
cell.imageText.textColor = .white
}
}

UITableView Checkmarks at the wrong place after search

I want to search in my tableView, set checkmarks and save the objects with the checkmarks in Realm. But if I set a checkmark after a search and cancel the search, the checkmark is at the indexPath that I clicked on, and not at the object. I can't explain it better, so here's an example:
After I search an exercise.
After I clicked the cancel button
Here's my code:
class ShowExcercisesTableViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate {
//Properties
let realm = try! Realm()
var request2: Results<Excercise>?{
didSet{
tableView.reloadData()
}
}
var searchOrNot: Excercise?
var searchResults = try! Realm().objects(Excercise.self)
var resultSearchController: UISearchController!
var shouldShowSearchResults = false
var muscleGroupForSearch: String?
//Searchbar Funktionen
func filterResultsWithSearchString(searchString: String){
let predicate = NSPredicate(format: "name CONTAINS [c]%# AND muscleGroup =%# AND copied = false", searchString, muscleGroupForSearch!)
searchResults = realm.objects(Excercise.self).filter(predicate).sorted(byProperty: "name", ascending: true)
}
func updateSearchResults(for searchController: UISearchController) {
let searchString = searchController.searchBar.text
filterResultsWithSearchString(searchString: searchString!)
tableView.reloadData()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
shouldShowSearchResults = true
tableView.reloadData()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
shouldShowSearchResults = false
tableView.reloadData()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if !shouldShowSearchResults {
shouldShowSearchResults = true
tableView.reloadData()
}
resultSearchController.searchBar.resignFirstResponder()
}
//Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.resultSearchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.searchBar.delegate = self
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.sizeToFit()
controller.searchBar.placeholder = "Suche Übungen..."
self.tableView.tableHeaderView = controller.searchBar
return controller
})()
self.tableView.reloadData()
}
//TableView Funktionen
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if shouldShowSearchResults {
return searchResults.count
}
else{
return request2!.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: ShowExcercisesTableViewCell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier.showExcercises, for: indexPath) as! ShowExcercisesTableViewCell
if shouldShowSearchResults{
let excercise = searchResults[indexPath.row]
cell.nameLabel.text = excercise.name
if fromTrainingPlan{
if excercise.selected == true{
cell.accessoryType = .checkmark
}
else{
cell.accessoryType = .none
}
}
return cell
}
else{
let excercise = request2![indexPath.row]
cell.nameLabel.text = excercise.name
if fromTrainingPlan{
if excercise.selected == true{
cell.accessoryType = .checkmark
}
else{
cell.accessoryType = .none
}
}
return cell
}
}
//Checkmarks
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if fromTrainingPlan == true && request2 != nil{
if shouldShowSearchResults{
searchOrNot = searchResults[indexPath.row]
}
else{
searchOrNot = request2![indexPath.row]
}
tableView.deselectRow(at: indexPath, animated: true)
let cell: ShowExcercisesTableViewCell = tableView.cellForRow(at: indexPath) as! ShowExcercisesTableViewCell
do {
try realm.write {
searchOrNot!.selected = !searchOrNot!.selected
}
}
catch{
print(error)
}
if searchOrNot!.selected {
cell.accessoryType = .checkmark
}
else {
cell.accessoryType = .none
}
}
}
Sorry for so much code, I'm not sure what is relevant and what not. Is there any way to set the checkmarks at the right places after the search? Thanks in advance!
It's working now.
In your cellForRowAtIndexPath, you need to disable the checkmark for cells that do not need it. You are only enabling for cells that do.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: ShowExcercisesTableViewCell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier.showExcercises, for: indexPath) as! ShowExcercisesTableViewCell
if shouldShowSearchResults{
let excercise = searchResults[indexPath.row]
cell.nameLabel.text = excercise.name
if excercise.selected == true{
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none // Add this code here
}
return cell
}
else{
let excercise = request2![indexPath.row]
cell.nameLabel.text = excercise.name
if excercise.selected == true {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none // Add this code here
}
return cell
}
}
UITableViews reuse the cells internally. So when you are searching, you are saying cell one has a checkmark, then when you cancel, it goes back to the table and looks at the cells and your cellForRow code never tells it that cell one is no longer checked, thus it maintains the checkmark there. The cell is not being recreated, its already exists, so you cannot make an assumption about what state it is in (not checked or checked).
the checkmark is at the indexPath that I clicked on
You are not telling the code on what indexPath you want the checkmark. When your cell gets reused :
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
You need to keep a reference to what indexPath is supposed to be selected and show the checkMark so the cells shows the checkMark on the correct indexPath when the cells are reused internally.
EDIT:
Seems some people downvote and modify my answers as their own without reading how the framework works and reading Apples Documentation.
Reusable Cells
prepareForReuse
If a UITableViewCell object is reusable—that is, it has a reuse
identifier—this method is invoked just before the object is returned
from the UITableView method dequeueReusableCellWithIdentifier:. For
performance reasons, you should only reset attributes of the cell that
are not related to content, for example, alpha, editing, and selection
state. The table view's delegate in tableView:cellForRowAtIndexPath:
should always reset all content when reusing a cell. If the cell
object does not have an associated reuse identifier, this method is
not called. If you override this method, you must be sure to invoke
the superclass implementation.

tableview data repeat when scrolling

I use a custom cell to show the placeholder but scrolling the table repeats the placeholder
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! AddTableViewCell
cell.textInfo.delegate = self
if textPlaceHolders![indexPath.row].containsString("Category") == true {
cell.selected = true
cell.textInfo.text = textPlaceHolders![indexPath.row]
cell.accessoryType = .DisclosureIndicator
} else {
cell.textInfo.placeholder = textPlaceHolders![indexPath.row]
}
return cell
}
I tried some solution like this the problem resolved but when user end edit the text disappear
class AddTableViewCell: UITableViewCell {
#IBOutlet weak var textInfo: UITextField!
override func prepareForReuse() {
textInfo.text= ""
}
}
In your case you assign text property for cell's textInfo outlet in one case and placeholder in another. Because of UITableView's reuse policy your textInfo contains placeholder/text even if you haven't specified it for concrete indexPath. So you need to clean it up for every indexPath if you don't want them. Like this:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! AddTableViewCell
cell.textInfo.delegate = self
if textPlaceHolders![indexPath.row].containsString("Category") == true {
cell.selected = true
cell.textInfo.text = textPlaceHolders![indexPath.row]
cell.textInfo.placeholder = nil
cell.accessoryType = .DisclosureIndicator
} else {
cell.textInfo.placeholder = textPlaceHolders![indexPath.row]
cell.textInfo.text = nil
}
return cell
}

Search Bar on TableView Does not Work

I'm trying to add a search bar to a simple table view consisting of 7 cells of names and small description for each name.
As in the image here:
I made a class in swift file called Business, that has two attributes: Name and Des.
Here's the code in the view controller:
class FirstViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var TableView: UITableView!
var B = [Business]() //candies
var filteredNames = [Business]()
let searchController = UISearchController(searchResultsController: nil)
func filterContentForSearchText(searchText: String, scope: String = "All") {
filteredNames = B.filter { Bu in
return Bu.Name.lowercaseString.containsString(searchText.lowercaseString)
}
TableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
B = [
Business(Name:"Mariah", Des:"I'm Here to help"),
Business(Name:"Nada", Des:"Hi"),
Business(Name:"Atheer", Des:"Hello"),
Business(Name:"Lojian", Des:"I can Help you"),
Business(Name:"Nadya", Des:"Hayat"),
Business(Name:"Omnia", Des:"Yahoo"),
Business(Name:"Eman", Des:"I have amazing stuff"),
Business(Name:"Amani", Des:"Yess")
]
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
TableView.tableHeaderView = searchController.searchBar
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.active && searchController.searchBar.text != "" {
return filteredNames.count
}
return B.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.TableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CellTableViewCell
cell.NameLabel.text = B[indexPath.row].Name
cell.DescriptionLabel.text = B[indexPath.row].Des
let Bu: Business
if searchController.active && searchController.searchBar.text != "" {
Bu = filteredNames[indexPath.row]
} else {
Bu = B[indexPath.row]
}
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cell
}
}
extension FirstViewController: UISearchResultsUpdating {
func updateSearchResultsForSearchController(searchController:
(UISearchController) {
filterContentForSearchText(searchController.searchBar.text!)
}
}
I followed this tutorial to do that:
https://www.raywenderlich.com/113772/uisearchcontroller-tutorial
I don't know whay when I tried to search in simulator the result is always the first cell: Mariah
What's wrong with the code?
You don't use the search result to populate the cells. Replace you cellForRowAtIndexPath with this:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.TableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CellTableViewCell
let Bu: Business
if searchController.active && searchController.searchBar.text != "" {
Bu = filteredNames[indexPath.row]
} else {
Bu = B[indexPath.row]
}
cell.NameLabel.text = Bu.Name
cell.DescriptionLabel.text = Bu.Des
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cell
}
And, don't use capital first letters for properties.

Resources