UITABLE view sections with different prototype cells in each section - swift

I have a table view with different sections and for each section it has different prototype cells. I have created the prototype cell in storyboard but I could not make more than one cell in cellForRowAtIndexPath. I have attached the whole code for reference.
This is my storyboard design
This is the final output screen which it should look like
import UIKit
class PlacePeopleViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var friendlistTableView: UITableView!
var sectionHead = ["Friends", "Others"]
override func viewDidLoad() {
super.viewDidLoad()
friendlistTableView.delegate = self
friendlistTableView.dataSource = self
// Do any additional setup after loading the view.
}
// MARK: - tableview datasource & delegate
func numberOfSections(in tableView: UITableView) -> Int {
return sectionHead.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sectionHead[section]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 5
}else {
return 10
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1") as! RecentVizzTableViewCell
cell.placeName.text = "poland"
cell.placeAddress.text = "Simon Albania"
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 79
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 15
}
}

Note : You can do this using only one cell. just hide/show the connect Button by checking some condition.
If you want to use different cells for different sections, inside your cellForRowAt indexPath method return your cells based on your section like below .
switch indexPath.section {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1") as! RecentVizzTableViewCellOne
return cell
default:
let defaultcell = tableView.dequeueReusableCell(withIdentifier: "defaultcell") as! RecentVizzTableViewCellDefatult
return defaultcell
}
hope this will help to you. good luck.

Related

TableView Rendering?

I have a table view that is rendering some static data into a UITableView but occasionally when running on a physical device the data is replaced with ? (see screenshot). I have listed the code below if anyone has an idea why this is occurring?
Here is the code for the table view
import UIKit
class OvenViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
extension OvenViewController : UITableViewDataSource,UITableViewDelegate{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return GridData.ovenTempConvArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: OvenCell.className, for: indexPath) as! OvenCell
let data = GridData.ovenTempConvArray[indexPath.row]
cell.lblFTemp.text = "\(data["f"] ?? "") F"
cell.lblCTemp.text = "\(data["c"] ?? "") C"
cell.lblGasMark.text = data["gm"]
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
}

tableView not showing data values

I am trying to get my tableView to show content in its cells, but it doesn't and I don't know why.
Here is the code. I also have connected the table view to the viewcontroller through dataSource and delegate in the storyboard, so that's why there are not typed in the viewDidLoad() method.
class ViewController: UIViewController, MKMapViewDelegate, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
wordsArray = [Words(sectionName: "Example section", usedWords: ["aaaaa", "aaaaa", "aaaaa"])]
tableView.alpha = 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return favCapitals.count
}
struct Words {
var sectionName: String! = ""
var usedWords: [String]! = []
}
var wordsArray: [Words] = []
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
cell.textLabel?.text = wordsArray[indexPath.section].usedWords[indexPath.row]
cell.textLabel?.textColor = .black
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let sectionName = "Favourite Capitals"
return sectionName
}
You will need to call the following methods before it listens to cellForRowAt:
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
another common problem is that the frame of the table is not set (e.g. inside a UITableViewCell, with automatic dimensions). The table requires a frame before it gets cells.
You can use tableView.reloadData() in the viewDidLoad Method.

how to implement segue from uitableviewcell to another tableviewcell

I have two view controller with tableviewcell and in both of them I can add items.
What I want to implement is that when I add items in the first tableviewcell lets say I add (item one , item two) and press on (item one).
I want to sugue to the second tableviewcell and add data.
BUT I want the data in the second tableviewcell to save separately,
that means, now if I press on (item one) I should see the data that I added
but if I press on (item two) it should be empty and I can add data later.
I have saved the data for the two tableviewcell in coredata.
I don't use segues or coredata in this solution, but the solution will fix what you need to some extent at least.
class vc1: UIViewController, UITableViewDelegate, UITableViewDataSource {
let tableView = UITableView()
let options: [Int] = [1,2]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return options.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return UITableViewCell()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = vc2()
//Not sure where to put the setup to be honest
//option 1:
vc.setupTableView(forCell: indexPath.item)
present(vc, animated: true) {
//option 2:
vc.setupTableView(forCell: indexPath.item)
}
}
}
class vc2: UIViewController, UITableViewDelegate, UITableViewDataSource {
let tableView = UITableView()
var selectedCell: Int!
//Having an nested array in an array will solve this custom "page" you are looking for
let results: [[String]] = [["test1", "test2"], ["test3", "test4"]]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func setupTableView(forCell cell: Int) {
selectedCell = cell
tableView.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return results[selectedCell].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel = results[selectedCell][indexPath.item]
return UITableViewCell()
}
}

Swift calling a class from a view controller

I am a beginner in swift coming from java. I have a task class and a taskcollection class where it is a collection of tasks. I am trying to put the collection into a table view but I dont know how.
This is task class:
class Task{
private var description : String
init(description: String){
self.description = description
}
func getDescription() -> String{
return self.description
}
func setDescription(description: String){
self.description = description
}}
This is taskCollection class:
class TaskCollection{
private var tasks: Array<Task>
init(){
self.tasks = [Task]()
}
func getTasks() -> Array<Task>{
return self.tasks
}
func addTask(task: Task){
self.tasks.append(task)
}}
To get the taskcollection into the tableview what do i do? In java I know I have to make something like new TaskCollection(), but i dont know how to get it in the tableviews:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ?
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// create a new cell if needed or reuse an old one
let cell:UITableViewCell = self.tableviewTasks.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
// set the text from the data model
cell.textLabel?.text = self.___?_____[indexPath.row]
return cell
}
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You tapped cell number \(indexPath.row).")
}
You would create an instance of the TaskCollection class somewhere in your ViewController file scope. Then you populate it somewhere else (I did this is viewDidLoad as an example). Number of rows will simply be the number of tasks in the taskCollection instance. You can access each task by using indexPath.row to get the index of the array of tasks.
class TableViewController: UITableViewController {
let taskCollection = TaskCollection()
override func viewDidLoad() {
super.viewDidLoad()
let task = Task(description: "Some Description")
taskCollection.addTask(task: task)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return taskCollection.getTasks().count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
let task = taskCollection.getTasks()[indexPath.row]
cell.textLabel?.text = task.getDescription()
return cell
}
}
First there is no need to create a TaskCollection class as it's functionality is already build in arrays so, you need to create an array of tasks
var tasksArr = [Task]()
//
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.tasksArr.count
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// create a new cell if needed or reuse an old one
let cell:UITableViewCell = self.tableviewTasks.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
// set the text from the data model
cell.textLabel?.text = self.tasksArr[indexPath.row].description
return cell
}
OR according to current implementation
var colc = TaskCollection()
//
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.colc.tasks.count
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// create a new cell if needed or reuse an old one
let cell:UITableViewCell = self.tableviewTasks.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
// set the text from the data model
cell.textLabel?.text = self.colc.tasks[indexPath.row].description
return cell
}

How do you add a second section with a different type of prototype cell to a tableview in Swift?

I have a tableview with 2 prototype cells in a view controller. I want each cell to display data from different arrays.
Below is my code. I can get the tableview to show jobs or schools, but not both. I don't understand how to make the table display cell1 (jobs) and then cell2 (schools) when each cell contains different data sources.
screenshot
Import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let jobs = ["McDonalds", "Hardees", "Taco Bell"]
let schools = ["Univ of CO", "Univ of TX", "Univ of CA"]
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return jobs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "JobsCell", for: indexPath) as! Jobs
let job = jobs[indexPath.row]
cell.jobLbl.text = job
return cell
}
}
Answer: I fixed this by adding numberOfSections function (thanks Robert). Updated code below if anyone else has this question:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let jobs = ["McDonalds", "Hardees", "Taco Bell"]
let schools = ["Univ of CO", "Univ of TX", "Univ of CA", "Univ of Camdenton"]
override func viewDidLoad() {
super.viewDidLoad()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (section == 0) {
return jobs.count
} else {
return schools.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "JobsCell", for: indexPath) as! Jobs
let job = jobs[indexPath.row]
cell.jobLbl.text = job
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "SchoolsCell", for: indexPath) as! Schools
let school = schools[indexPath.row]
cell.schoolLbl.text = school
return cell
}
}
}
It sounds like you want to display one section with cells for jobs followed by a second section with cells for schools. If that's the case, you'll need to set the number of sections to 2, then rewrite your delegate functions to respond appropriately depending on the section number.
So numberOfRowsInSection is going to have to check the section number, then return the number of rows for that specific section. And cellForRowAt will need to check the section, then set up and return either a job or a school cell for the given row.
Here's what that would look like in your example:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let jobs = ["McDonalds", "Hardees", "Taco Bell"]
let schools = ["Univ of CO", "Univ of TX", "Univ of CA"]
override func viewDidLoad() {
super.viewDidLoad()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch(section) {
case 0: return jobs.count
default: return schools.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch(indexPath.section) {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "JobsCell", for: indexPath) as! Jobs
let job = jobs[indexPath.row]
cell.jobLbl.text = job
return cell
default:
let cell = tableView.dequeueReusableCell(withIdentifier: "SchoolsCell", for: indexPath) as! Schools
let school = schools[indexPath.row]
cell.schoolLbl.text = school
return cell
}
}
}
And here's the output in the simulator: