Implementation of tableView cellForRowAt with a nested function - swift

In on of the git repositories I found pretty weird implementation of tableView cellForRowAt method.
The method have inside implementation of configureCell method. Isn't that wrong ? Let say.. for 1000 cells in table view - it is going to create this method about 1000 thousand times ? Can any one tell me if it is good way in swift or not ? I suppose it is totally wrong.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
func configureVehicleCell(_ object: CustomModel) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCellTableViewCell
if object.hasIssues {
cell.dvirImageView.isHidden = false
}
if object.cmv {
cell.cmvImageView.isHidden = false
}
cell.titleLabel.text = object.name
cell.subtitleLabel.text = object.someName
cell.tag = Int(object.id)
return cell
}
if lastUsedId == nil {
return configureCell(objectArray[(indexPath as NSIndexPath).row])
} else {
if (indexPath as NSIndexPath).section == 0 {
return configureCell(lastUsed!)
} else {
return configureCell(objectsArray[(indexPath as NSIndexPath).row])
}
}
}
In my opinion it should look like:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if lastUsedId == nil {
return configureCell(objectArray[(indexPath as NSIndexPath).row])
} else {
if (indexPath as NSIndexPath).section == 0 {
return configureCell(lastUsed!)
} else {
return configureCell(objectsArray[(indexPath as NSIndexPath).row])
}
}
}
func configureVehicleCell(_ object: CustomModel) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCellTableViewCell
if object.hasIssues {
cell.dvirImageView.isHidden = false
}
if object.cmv {
cell.cmvImageView.isHidden = false
}
cell.titleLabel.text = object.name
cell.subtitleLabel.text = object.someName
cell.tag = Int(object.id)
return cell
}

Related

Load More when reaching the end of a UITableView

I am trying to implement a load more function within a table view. I read the that code would go inside of the cellForRowAt func, but this is not working.
I have two UITableViews in this specific ViewController. Everything is working great until this.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (tableView == userSearchesTableView) {
if let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? CellBasicItemInfo {
cell.isUserInteractionEnabled = true
let responseItems = userRecentSearches[indexPath.row]
cell.configureCell(item: responseItems)
cell.setNeedsLayout()
return cell
} else {
return CellBasicItemInfo()
}
} else {
if let cell = tableView.dequeueReusableCell(withIdentifier: "itemCell", for: indexPath) as? CellItems {
cell.isUserInteractionEnabled = true
let responseItems = resultsModelArray[indexPath.row]
cell.configureCell(item: responseItems)
cell.setNeedsLayout()
if (indexPath.row == self.resultsModelArray.count) {
print("REACHED THE BOTTOM") // does not print
}
return cell
} else {
return CellItems()
}
}
}
Is there another or better way to handle this functionality?
per comment (did not work)
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if (tableView == userSearchesTableView) {
if (indexPath.row == self.userRecentSearches.count) {
print("REACHED THE BOTTOM RECENT")
}
}
}
UPDATE
adding the follow worked for me.
...
if (indexPath.row == self.userRecentSearches.count - 2) {
print("REACHED THE BOTTOM RECENT")
}
...

"Index out of range" Error with two Tableviews in one Viewcontroller

I have two Tableviews in one ViewController. But if I run this my code I will get this error on line let post = posts[indexPath.row]:
"Index out of range"
I think it has be something with the posts.count, but I can't figure it out. When I ran this code without the second Tableview Tableview_moremaps everything works just fine.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if comments.count == 0 {
self.tableView.setEmptyMessage("No comments yet!")
} else {
self.tableView.restore()
}
if posts.count == 0 {
self.Tableview_moremaps.setEmptyMessage("No other maps yet!")
}else{
self.Tableview_moremaps.restore()
}
if tableView == tableView {
return comments.count
}else{
return posts.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == self.tableView {
let cell = tableView.dequeueReusableCell(withIdentifier: "Comment", for: indexPath) as? CommentTableViewCell
let comment = comments[indexPath.row]
cell?.comment = comment
cell?.delegate = self
return cell!
} else if tableView == Tableview_moremaps {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? MoremapsTableViewCell
cell?.Map_image.image = nil
let post = posts[indexPath.row]
cell?.post = post
cell?.delegate = self
return cell!
}
return UITableViewCell()
}
In numberOfRowsInSection, update the if-condition
if tableView === self.tableView {
return comments.count
} else {
return posts.count
}
Currently tableView == tableView is always true and returned value is comments count.
I think the problem is in the way you're using cellForRowAt
Try giving each tableview an identifier with tableView.accessibilityIdentifier = "myIdentifier"
and then cellForRowAtwould be like following:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView.accessibilityIdentifier == "myIdentifier" {
let cell = .....
...
...
...
...
...
you can try this
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.tableView {
return comments.count
}
else{
return posts.count
}
}
//Your this code is perfect.(no issue here)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == self.tableView {
let cell = tableView.dequeueReusableCell(withIdentifier: "Comment", for: indexPath) as? CommentTableViewCell
let comment = comments[indexPath.row]
cell?.comment = comment
cell?.delegate = self
return cell!
} else if tableView == Tableview_moremaps {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? MoremapsTableViewCell
cell?.Map_image.image = nil
let post = posts[indexPath.row]
cell?.post = post
cell?.delegate = self
return cell!
}
return UITableViewCell()
}

How to divide tableview to sections and give headlines

I have a tableview in my app.
I want to divide my cells into sections and give headlines.
Below I attach the picture (animals, birds headlines):
How do I do that in dynamic prototype cells?
My section data:
var sectionsData = [
"header",
"description",
"diagnoses",
"perscription",
"notes",
"addFaxHeadline",
"addFax",
"addEmailHeadline",
"addEmails",
"givePermissionHeadline",
"select answer"
]
Here is my cell at row function:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print ("indexPath: ", indexPath)
print ("indexPath: ", indexPath[0])
print ("-------")
if (sectionsData[indexPath[0]] == "header") {
let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell", for: indexPath)
return cell
} else if (sectionsData[indexPath[0]] == "description") {
let cell = tableView.dequeueReusableCell(withIdentifier: "headerInfoCell", for: indexPath)
return cell
} else if (sectionsData[indexPath[0]] == "diagnoses") {
let cell = tableView.dequeueReusableCell(withIdentifier: "diagnosisCell", for: indexPath)
return cell
} else if (sectionsData[indexPath[0]] == "perscription") {
let cell = tableView.dequeueReusableCell(withIdentifier: "perscriptionCell", for: indexPath)
return cell
} else if (sectionsData[indexPath[0]] == "notes") {
let cell = tableView.dequeueReusableCell(withIdentifier: "notesCell", for: indexPath)
return cell
} else if (sectionsData[indexPath[0]] == "addFaxHeadline") {
let cell = tableView.dequeueReusableCell(withIdentifier: "addFaxCell", for: indexPath)
return cell
} else if (sectionsData[indexPath[0]] == "addFax") {
let cell = tableView.dequeueReusableCell(withIdentifier: "emailNameCell", for: indexPath)
return cell
} else if (sectionsData[indexPath[0]] == "addEmailHeadline") {
let cell = tableView.dequeueReusableCell(withIdentifier: "addEmailCell", for: indexPath)
return cell
} else if (sectionsData[indexPath[0]] == "addEmails") {
let cell = tableView.dequeueReusableCell(withIdentifier: "emailNameCell", for: indexPath)
return cell
} else if (sectionsData[indexPath[0]] == "givePermissionHeadline") {
let cell = tableView.dequeueReusableCell(withIdentifier: "permisionCell", for: indexPath)
return cell
} else if (sectionsData[indexPath[0]] == "select answer") {
let cell = tableView.dequeueReusableCell(withIdentifier: "selectAnswerCell", for: indexPath)
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: "addFaxCell", for: indexPath)
// <<<< ???
return cell
}
and my numbers in row per section function:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if (sectionsData[section] == "header") {
print ("returning 1 ?")
return 1
} else if (sectionsData[section] == "description") {
return 1
} else if (sectionsData[section] == "diagnoses") {
//return visitSummary.diagnoses.count
return 2
} else if (sectionsData[section] == "perscription") {
//return visitSummary.prescriptions.count
return 2
} else if (sectionsData[section] == "notes") {
return 1
} else if (sectionsData[section] == "addFaxHeadline") {
return 1
} else if (sectionsData[section] == "addFax") {
return faxAdded.count
} else if (sectionsData[section] == "addEmailHeadline") {
return 1
} else if (sectionsData[section] == "addEmails") {
return emailsAdded.count
} else if (sectionsData[section] == "givePermissionHeadline") {
return 1
} else if (sectionsData[section] == "select answer") {
return 1
} else {
return 0
}
return 0
}
and my number of sections:
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
print ("sectionsData.count: ", sectionsData.count)
return sectionsData.count
}
All of the tutorials I find is for one section and I have a very amount of sections to show.
How would I divide it and give them headlines?
Let's clean up your code first:
enum Section: Int, CaseIterable {
case header = 0, description, diagnoses, prescription, notes, addFaxHeadline, addFax, addEmailHeadline, addEmails, givePermissionHeadline, selectAnswer
}
var sectionData: [Section] = [
.header,
.description,
.diagnoses
...
]
override func numberOfSections(in tableView: UITableView) -> Int {
return sectionsData.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection sectionIndex: Int) -> Int {
let section = sectionData[sectionIndex]
switch section {
case .header:
return 1
case .description:
return 1
// ...
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let section = sectionData[sectionIndex]
switch section {
case .header:
let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell", for: indexPath)
return cell
// ... etc
}
}
Now, we can return section title just using a String:
override func tableView(_ tableView: UITableView, titleForHeaderInSection sectionIndex: Int) -> String? {
let section = sectionData[sectionIndex]
switch section {
case .header:
return "Header title"
case .description:
return "Description title"
default:
return nil
}
}
Another option is to use tableView(:viewForHeaderInSection:) and tableView(:heightForHeaderInSection:):
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView()
let label = UILabel()
view.addSubview(label)
// setup constraints accordingly
// setup title of the label
return view
}
You can also use a custom reusable header which would be registered and dequeued in the same way cells are dequeued.
var sectionsData = [
"header",
"description",
"diagnoses",
"prescription",
"notes",
"addFaxHeadline",
"addFax",
"addEmailHeadline",
"addEmails",
"givePermissionHeadline",
"select answer"
] // Your Array
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? //*Data Source method for header title*
{
// Safe cast
if let sectionArray = sectionsData as? [String]
{
return sectionArray[section]
}
// A fail safe
return "No Header"
}
Now I see. You are misunderstanding how these methods work. They are called for every cell in every section.
So, if you return 4 in numberOfSections, the method numberOfRowsInSection will be called 4 times, and sectionIndex (now called section in latest versions) will have the current section (0 to 3 in our example).
Therefore, if you want to call the second section "Birds" and let all the others nil, your code will look like this:
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 1 {
return "Birds"
}
// Otherwise
return nil
}
Same thing for how many rows each section will have:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
// 1 row for the first section
return 1
} else if section == 1 {
// 3 rows for the second section
return 3
}
// 2 rows for every other section
return 2
}
And, finally, what cell will be used in each indexPath:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Figure out which row and section you are talking about
let row = indexPath.row
let section = indexPath.section
// Now you know where you are in the TableView, create the corresponding cell according to your project
// Start by dequeueing a custom cell using the identifier and forcing the cell to become your custom cell
let cell = tableView.dequeueReusableCell(withIdentifier: customCellID) as! CustomTableViewCell
// Do aditional setup to this cell
cell.textLabel?.text = "This is cell \(row) in section \(section)"
// Return the cell when you are ready
return cell
}
Remember Sulthan's suggestion to create an enum for your sections.

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.

Swift - How can I select multiple rows in tableview without segue

My development environment is swift3, xcode8.
I'm making a list app like Apple's message app.
When I select the list in the table view, I go to the detail page (through the seg) and now I want to implement multiple delete functions, but there's a problem. When I edit mode, I can see the selection window, but if I select that selection window, just go to the detail page.
Maybe before going to the detail page through Seg. I think I should make it a multiple choice. What should I do?
Make sure you conform something like below code;
class TableviewController:UITableViewController{
override func viewDidLoad() {
super.viewDidLoad()
var isMultipleSelectionActive = false
var selectedItems: [String: Bool] = [:]
tableView.allowsMultipleSelectionDuringEditing = true
tableView.setEditing(true, animated: false)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.textLabel?.text = "\(indexPath.row)"
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedItem = items.objectAtIndex(indexPath.row)
//add to selectedItems
selectedItems[selectedItem] = true
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let selectedItem = items.objectAtIndex(indexPath.row)
// remove from selectedItems
selectedItems[selectedItem] = nil
}
func getStatusOfSelectedItems() {
for item in selectedItems {
println(item)
}
}
//You should override shouldPerformSegueWithIdentifier and return false if isMultipleSelectionActive is true
override func shouldPerformSegue(withIdentifier identifier: String?, sender: Any?) -> Bool {
if let identifierName = identifier {
if identifierName == "NameOfYourSegueIdentifier" {
if isMultipleSelectionActive {
return false
}
}
}
return true
}
}
This code used to select the multiple row
class TableViewController: UITableViewController
{
var lastSelectedIndexPath = NSIndexPath(forRow: -1, inSection: 0)
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath)
// Configure the cell...
cell.textLabel!.text = "row: \(indexPath.row)"
if cell.selected
{
cell.selected = false
if cell.accessoryType == UITableViewCellAccessoryType.None
{
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
}
else
{
cell.accessoryType = UITableViewCellAccessoryType.None
}
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let cell = tableView.cellForRowAtIndexPath(indexPath)
if cell!.selected
{
cell!.selected = false
if cell!.accessoryType == UITableViewCellAccessoryType.None
{
cell!.accessoryType = UITableViewCellAccessoryType.Checkmark
}
else
{
cell!.accessoryType = UITableViewCellAccessoryType.None
}
}
}