Creating a tableView on each cycle of for loop. Swift - ios

I am trying to create a tableView for each value in my array and I am not sure how to go about creating that. The code below clearly doesn't work I just used it to illustrate my point. How do I differentiate between tables in the tableView protocol functions.
let array = ["1","2","3","4","5"]
for value in array{
let newTableView: UITableView()
//Continue with creation of table
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.tableContent.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return cell
}
Any help is appreciated and please comment if the question is unclear

Previously, I have needed multiple TableViews or Collection Views in a single ViewController, e.g. for different tabs.
You can identify each table by using the tag property.
let data : [Int : [YourObjects]]
for key, value in data {
let newTableView: UITableView()
// Identify the table
newTableView.tag = key
newTableView.dataSource = self
//Continue with creation of table
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.data[tableView.tag].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Dequeue cell
// Get the data for this table, identified by the tag
let tableData = data[tableView.tag]
cell.populateCell(withData: tableData[indexPath.row])
return cell
}

Related

How do I solve the uiTableview scrolling app crash which throws array index out of bound exception in swift?

I am loading data and updating the cell, when I scroll quickly the app crashes and throws array index out of bound at cellforrowat: index path. How do I overcome this problem?
Your tableView is trying to access data from your data source which actually does not exist.
Assuming you have a data source like this.
let dataSource = [[String]]()
Then your table view delegate methods should look like this.
func numberOfSections(in tableView: UITableView) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let data = dataSource[indexPath.section][indexPath.row]
//your code
}

how to move a table view cell from one table view to a new table view

Currently, I am trying to move a tableview cell from one table view to another. I can't seem to get the proper mechanics down and need help with this task.
Right now I have an array that is not filled with any goals for my progress table view cells.
var goals: [String] = []
Here is the setup for the rest of this progress table view.
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return goals[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TodayGoalViewCell_1", for: indexPath) as? GoalTableViewCell
cell?.goalLabel.text = goals[indexPath.section][indexPath.row]
cell?.cellDelegate = self
cell?.index = indexPath
return cell!
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
func numberOfSections(in tableView: UITableView) -> Int {
return goals.count
}
In a separate file I have another table view that is already filled with goals. Here is the code:
var goals = ["goal 1", "goal 2", "goal 3"]
extension GoalsViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Goals.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "GoalConversationsCell_1", for: indexPath)
cell.textLabel?.text = Goals[indexPath.row]
cell.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
cell.textLabel?.numberOfLines = 3
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 0 {
Goals.remove(at: indexPath.row)
Goals.count != 0 {
showGoalSelected()
} else {
Goals.append(contentsOf: theEmptyModel)
}
tableView.reloadData()
}
}
}
I would like to make it so that when a user selects a goal from the table view which already had goals, that these goals are moved to the progress table view. How would I do this?
If there is a button inside your cell and you want to get news when this button is clicked, you need to look at the protocol-delegate pattern.
But you can also try to remove the button inside the cell and use a text label. To use the didSelectRowAt method to catch clicking on cell, tableView in delegete.
I do not know what kind of design and structure you have, I just offer you perspective.

UseDefault Create the issue in the tableView method

I just create the Bus ticket booking app. Now i want to save the search history (City Name and Date) and Display in my tableView. So this is what i coding in my SearchButtonAction.
#IBAction func btnSearchAction(_ sender: Any) {
if txtTo.text != nil && txtFrom.text != nil {
arrTo.append(txtTo.text!)
arrFrom.append(txtTo.text!)
UserDefault.set(arrTo, forKey: "arrTo")
UserDefault.set(arrFrom,forKey: "arrFrom")...
}
}
Now on my historyViewController I just coding like below
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrFrom.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RecentCell") as! RecentCell
cell.selectionStyle = .none
cell.lblFrom.text = arrFrom[indexPath.row]
cell.lblTo.text = arrTo[indexPath.row]
tblSearch.reloadData()
return cell
}
So it's Call only numberOfRowsInSection Method again and again Even arr count is more than one. What is the correct way to save two textField text in UserDefaults.
Remove reloading datas of tblSearch from cellForRowAt TableView data source method
When you reload tableview inside cellForRowAt method, tableview will go into looping. So you tableview won't display. So please remove tblSearch.reloadData() this line from cellForRow methhod.
please check screenshot, so you will get the better idea about looping.
http://prntscr.com/lte2mo

fatal error: Index out of range swift

I am facing Index out of range issue in UITableView.
Below is my code :
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
//== Teble: number of tables ==============================//
func numberOfSections(in tableView: UITableView) -> Int {
return headerTitleArray.count
}
//== Teble rows: number of rows ==============================//
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellTitleMultiArray.count
}
//== Teble rows: data for each row ==============================//
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableViewCell
let text = cellTitleMultiArray[indexPath.section][indexPath.row]
cell.titleLabel.text = text
return cell
}
}
I am trying to solve this issue but couldn't .Please please help me solve this issue....
It looks like your cellTitleMultiArray is an array of arrays, where the outer array contains an entry for each section, and for each section, the inner array at that index contains entries for each row in that section.
Thus numberOfSections(in:) should probably return the number of entries in cellTitleMultiArray.
tableView(_:numberOfRowsInSection:) should probably return the number of entries in the cellTitleMultiArray sub-array at the current section. See if you can work out that bit of code.

Swift: Is there any way to omit certain section header cells?

I have a dictionary which will be a data source for my tableView.
However, I want to add also other cells that are not the part of the dictionary, which means that they should not be under the section title that comes from dictionary.
To give you a better notion of what I'm trying to achieve I created this exemplary project available here
Here is the ViewController implementation, I tried to keep it as short as possible:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let dict2:Dictionary<String,[String]> = ["SECTION1":["This should be under section", "This should be under section too"]]
var dictKeysSorted:[String] = []
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
dictKeysSorted = dict2.keys.sort()
self.tableView.delegate = self
self.tableView.dataSource = self
// Do any additional setup after loading the view, typically from a nib.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (dict2 as NSDictionary).objectForKey(dictKeysSorted[section])!.count + 1
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return dictKeysSorted[section]
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30.0
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return dictKeysSorted.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: CustomCell = tableView.dequeueReusableCellWithIdentifier("cell") as! CustomCell
if indexPath.row == 0
{
cell.label.text = "This cell should be above section"
}
else
{
cell.label.text = (dict2 as NSDictionary).objectForKey(dictKeysSorted[indexPath.section])![indexPath.row-1] as? String
}
return cell
}
}
This is what I get:
My first idea was to create another record in my dictionary and simply omit it using if-statement in
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
But this is not the proper solution since it keeps returning an extra empty section header.
How to make tableView "omits" certain section headers?
Thanks in advance
PS. I found it difficult to name this thread properly, if you have any idea how to name it in a more relevant way, feel free to edit the title of this question.
You can implement the UITableViewDelegate method that returns the height of the header returning 0 for the header that you want to hide:
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
Here is the reference.
As stated in the doc, since iOS5 returning an empty header view or an empty title no longer result in an invisible header.
Please note that this will require you to return the default height for the sections that you want to show.

Resources