With the code below, I want to print the name and the price in each table cell. The build is done without any problem, but when I run the app, it says Bad Instruction error in the var item1 = arrData[i]["name"]
Here's the full code:
class ViewController3: UIViewController, UITableViewDelegate,
UITableViewDataSource {
let arrData: [[String:Any]] = [
["name": "spiderman", "price": 5000],
["name": "superman", "price": 15000],
["name": "batman", "price": 3000],
["name": "wonder woman", "price": 25000],
["name": "gundala", "price": 15000],
]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrData.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "Cell"
var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
var i = 0
while i <= arrData.count {
var item1 = arrData[i]["name"]
var item2 = arrData[i]["price"]
cell?.textLabel?.text = "\(item1) \(item2)"
i = i + 1
}
return cell!
}
}
Instead of while loop use indexPath.row to use show proper data at each row in your UITableView. And use reusable cell like below:
let identifier = "Cell"
override func viewDidLoad() {
super.viewDidLoad()
tableview.register(UITableViewCell.self, forCellReuseIdentifier: identifier)
tableview.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
let item1 = arrData[indexPath.row]["name"]
let item2 = arrData[indexPath.row]["price"]
cell.textLabel?.text = "\(item1!) \(item2!)"
return cell
}
Fix this piece while i < arrData.count. Index is out of bounds.
When you use instruction i <= arrData.count for 5th index you will get crash. You should change to, or better to use for in instruction
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "Cell"
var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
var i = 0
while i < arrData.count {
var item1 = arrData[i]["name"]
var item2 = arrData[i]["price"]
cell?.textLabel?.text = "\(item1) \(item2)"
i = i + 1
}
return cell!
}
Subscript of array is start from zero. It means the first element is not arrData[1] but arrData[0]. so while i <= arrData.count will cause out of bounds of array.
Try while i < arrData.count
PS, codes in tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) is wired, why you add a while loop? it will cause all cell of table view looks same.
Related
I have stuck up with an issue where I have a UITableView with a label and button in each row when the button is clicked from a particular row it will navigate to the next view and it has UITableView with a country list, when selected the country it will popup to the previous view and I want to update the country name with selected row, Could someone guide me how to update it. Below is my code. TIA
FirstViewController.swift
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableCell
let dict = customData[indexPath.row] as? NSObject
cell.lblTitle.text = "Title"
// cell.lblSubTitle.text = ""
cell.selectedButton.tag = indexPath.row
cell.selectedButton.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
return cell
}
#objc func buttonClick(sender: UIButton){
let customCell = CountryViewController(nibName: nil, bundle: nil)
self.navigationController?.pushViewController(customCell, animated: true)
}
CountryViewController.swift
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CountryCell", for: indexPath) as! CountryTableCell
cell.lblTitle.text = CountryList[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCountry = CountryList[indexPath.row]
self.navigationController?.popViewController(animated: true)
}
You can use delegation pattern:
protocol SelectCountry {
func countrySelected(withName countryName: String)
}
in your FirstViewController.swift conform to that protocol
extension FirstViewController: SelectCountry {
func countrySelected(withName countryName: String) {
// Assign country name to your label here
}
in your CountryViewController.swift make a variable called delegate/anyName you want
var delegate: SelectCountry?
in your buttonClick method
customCell.delegate = self
in your CountryViewController in didSelectRowAt method
delegate?.countrySelected(withName: CountryList[indexPath.row])
your label will be updated with country name you selected in CountryViewController.
NOTE: Names are just placeholders here you can use your own names for protocol/methods
First Controller:
"CountrySelectionDelegate" confirm this delegate in your first controller
Next, Pass/Store your FirstViewController cell selection index.
Go to your Country Controller, Select country, Pass it through "func selectedCountry(country: String,index: Int) {}" , Update your custom Data/Array.
Lastly reload your Table view with updated Custom data.
class FirstViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,CountrySelectionDelegate {
#IBOutlet weak var yourFirstTable: UITableView!
var customData = [Details(title: "Title-1", country: ""),Details(title: "Title - 2", country: ""),]
override func viewDidLoad() {
super.viewDidLoad()
}
func selectedCountry(country: String,index: Int) {
self.customData[index].country = country
yourFirstTable.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return customData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! DetailTableCell
let custInfo = customData[indexPath.row]
cell.yourTitleLabel.text = "Title: " + custInfo.title
cell.yourCountryLabel.text = (custInfo.country.count > 0 ? "Country: \(custInfo.country)" : "Country: ---")
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "CountryViewController") as? CountryViewController
nextVC?.selectedIndex = indexPath.row
nextVC?.delegate = self
self.navigationController?.pushViewController(nextVC!, animated: true)
}
}
CountryViewController:
import UIKit
protocol CountrySelectionDelegate {
func selectedCountry(country: String, index:Int)
}
class CountryViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var countryTable: UITableView!
var selectedIndex: Int = 0
let countryList = ["India","USA","UK","Nepal","Bangladesh","Pakistan","Bhutan"]
weak var delegate: CountrySelectionDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return countryList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CountryTableViewCell
cell.countryLabel.text = countryList[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
delegate?.selectedCountry(country: countryList[indexPath.row], index: selectedIndex)
self.navigationController?.popViewController(animated: true)
}
}
I want to display two array values in tableview using single cell.
Suppose i have two array and both contains same no of elements.
FirstArray and SecondArray. there is two label in tableview cell Lbl1 and Lbl2, now Lbl1 should fill with FirstArray and Lbl2 Should fill with SecondArray. I know that we can not use two array for uitableview datasource . I can not figure out how to do this.
Please help me.
I also tried using multiple custom tableview cells with section. but it did not give the desired result.
I have two Array -
let datalist1 = ["firstCell1" , "firstCell2" , "firstCell3" , "firstCell4"]
let datalist2 = ["secondCell1" ,"secondCell2" , "secondCell3" ,"secondCell4"]
In tableview numberOfRowsInSection :
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0
{
return datalist1.count
}
else {
return datalist2.count
}
}
In cellForRowAt :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as? FirstCell
cell?.initData(name: datalist1[indexPath.row])
return cell!
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as? SecondCell
cell?.initData(lbl: datalist2[indexPath.row])
return cell!
}
}
Actual Output :
FirstCell1
FirstCell2
FirstCell3
FirstCell4
SecondCell1
SecondCell2
SecondCell3
SecondCell4
Expected Output:
FirstCell1
SecondCell1
FirstCell2
SecondCell2
FirstCell3
SecondCell3
FirstCell4
SecondCell4
Hello You not need to add two section just do as bellow.
This is your arrays.
let datalist1 = ["firstCell1" , "firstCell2" , "firstCell3" , "firstCell4"]
let datalist2 = ["secondCell1" ,"secondCell2" , "secondCell3" ,"secondCell4"]
Number of rows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datalist1.coun
}
Cell for row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as? FirstCell
cell.Lbl1.text = datalist1[indexPath.row]
cell.Lbl2.text = datalist2[indexPath.row]
return cell!
}
Based on the explanation and code, you have provided, the requirement is not clear.
However, there may be two cases based on the above details:
Case-1:
Cell-1 : FirstCell1
Cell-2 : SecondCell1
Cell-3 : FirstCell2
Cell-4 : SecondCell2
Then you can implement something like below:
In tableview numberOfRowsInSection :
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (datalist1.count + datalist2.count)
}
In cellForRowAt :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row % 2 == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as? FirstCell
cell?.initData(name: datalist1[indexPath.row])
return cell!
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as? SecondCell
cell?.initData(lbl: datalist2[indexPath.row])
return cell!
}
}
Case-2:
Cell-1 : FirstCell1 SecondCell1
Cell-2 : FirstCell2 SecondCell2
Cell-3 : FirstCell3 SecondCell3
Cell-4 : FirstCell4 SecondCell4
Then you can implement something like below:
In tableview numberOfRowsInSection :
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datalist1.count
}
In cellForRowAt :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as? FirstCell
//Single custom cell can implement both the labels
cell?.initData(name: datalist1[indexPath.row],lbl: datalist2[indexPath.row])
return cell!
}
}
You've to Declare as
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section %2 == 0 {
let cell1 = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as? FirstCell
cell1.lbl1.text = datalist1[indexPath.row]
return cell1!
}
else {
let cell2 = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as? SecondCell
cell2.lbl2.text = datalist2[indexPath.row]
return cell2!
}
}
The best way is using models. You have to declare data model such as
struct MyModel {
var firstValue: String?
var secondValue: String?
}
Then you have to convert your two arrays to a single array of MyModel objects
var myData = Array<MyModel>()
Then by using for loop you can iterate over one array and fill the myData array.
for (index, _) in datalist1 {
let object = MyModel()
object.firstValue = datalist1[index]
object.firstValue = datalist2[index]
myData.append(object)
}
Then just implement tableview protocol methods and fill your custom cell with MyModel objects.
1. Create a single array from datalist1 and datalist2 using zip(_:_:), that we'll be using as dataSource for tableView.
lazy var dataList = Array(zip(self.datalist1, self.datalist2))
dataList is of type [(String, String)].
Example:
If datalist1 and datalist2 are,
let datalist1 = ["firstCell1" , "firstCell2" , "firstCell3" , "firstCell4"]
let datalist2 = ["secondCell1" ,"secondCell2" , "secondCell3" ,"secondCell4"]
then, dataList contains
[("firstCell1", "secondCell1"), ("firstCell2", "secondCell2"), ("firstCell3", "secondCell3"), ("firstCell4", "secondCell4")]
2. You need a single cell to display all that data. There is no need to create 2 different UITableViewCells for this. Example:
class CustomCell: UITableViewCell {
#IBOutlet weak var lbl1: UILabel!
#IBOutlet weak var lbl2: UILabel!
}
3. Now, your UITableViewDataSource methods look like,
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
cell.lbl1.text = self.dataList[indexPath.row].0
cell.lbl2.text = self.dataList[indexPath.row].1
return cell
}
class ViewController: UIViewController , UITableViewDelegate , UITableViewDataSource{
#IBOutlet weak var tableView: UITableView!
var questions:[Question] = []
var sectionCountGlobal = 0
override func viewDidLoad() {
super.viewDidLoad()
questions = fillQuestions()
}
func fillQuestions()-> [Question]{
var temp : [Question] = []
var choices : [Choice] = []
let choice = Choice(id: 1, text: "choice ", status: 1, questionId: 1)
choices.append(choice)
choices.append(choice)
choices.append(choice)
choices.append(choice)
choices.append(choice)
choices.append(choice)
let q1 = Question(id: 1, text: "Ahmad 55 years old man with a history of hypertension and hypocholesteremia was in a wedding and during the party he starts to feel chest pain and dizzy, his wife brought him to the emergency department. The ER nurse checked his vital signs: BP 88/50, HR: 45, RR:10, SPaO2: 90% and O2 per nasal cannula was started at 4l/minute. Few seconds later Mr.Ahmad lost consciousness and the code blue team were activated.", choices: choices)
let q2 = Question(id: 1, text: "question 2", choices: choices)
let q3 = Question(id: 1, text: "question 3", choices: choices)
temp.append(q1)
temp.append(q2)
temp.append(q3)
return temp
}
func numberOfSections(in tableView: UITableView) -> Int {
return questions.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
sectionCountGlobal = section
return questions[section].choices.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0{
let questionTextCell = tableView.dequeueReusableCell(withIdentifier: "QuestionTextCell") as! QuestionTextCell
questionTextCell.setQuestionText(text: questions[indexPath.section].text)
return questionTextCell
}else{
let choiceCell = tableView.dequeueReusableCell(withIdentifier: "ChoiceCell") as! ChoiceCell
choiceCell.choiceText.text = questions[indexPath.section].choices[indexPath.row].text
return choiceCell
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let questionNumber = "Q" + String(section+1)
return questionNumber
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 3
}
override func viewWillAppear(_ animated: Bool) {
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
}
}
I am working on a quiz app and there is multiple choices for each question so when checking the radio button in a cell and scroll to other cells i found that the other cells got checked without touching them what is the solution.
I tried different cell reusing methods also prepareForReuse() and nothing works how can i treat each cell independently without affect from other cells , i don't know the number of questions it is come from server.
In your cellForRowAt implementation you have to reset the cell's state according to whether it is selected or not. Due to cell reuse, you can get a cell which was previously selected, but now should not be selected - in that case you have to tell the cell to get unselected (and vice versa):
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0{
let questionTextCell = tableView.dequeueReusableCell(withIdentifier: "QuestionTextCell") as! QuestionTextCell
questionTextCell.setQuestionText(text: questions[indexPath.section].text)
return questionTextCell
} else {
let choiceCell = tableView.dequeueReusableCell(withIdentifier: "ChoiceCell") as! ChoiceCell
// here detect if the cell should be selected and set it accordingly, so something like:
let isSelected = isSelectedChoice(questions[indexPath.section].choices[indexPath.row])
choiceCell.isSelected = isSelected
// of course this is just a mockup, since I don't know exactly how you manage selection,
// but it should get you on the right path
choiceCell.choiceText.text = questions[indexPath.section].choices[indexPath.row].text
return choiceCell
}
}
The issue in you code is you not changing the status of your radio button. When you select the option from didSelectRowAt method, you have to change the status of your choice. As per your choice model you can change the status of particular choice status. Following are both method that can manage your selection of choice(your status variable should be Bool type):
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0{
let questionTextCell = tableView.dequeueReusableCell(withIdentifier: "QuestionTextCell") as! QuestionTextCell
questionTextCell.setQuestionText(text: questions[indexPath.section].text)
return questionTextCell
}else{
let choiceCell = tableView.dequeueReusableCell(withIdentifier: "ChoiceCell") as! ChoiceCell
// update your radio button UI
choiceCell.radioButton.isSelected = questions[indexPath.section].choices[indexPath.row].status
choiceCell.choiceText.text = questions[indexPath.section].choices[indexPath.row].text
return choiceCell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
questions[indexPath.section].choices[indexPath.row].status = !questions[indexPath.section].choices[indexPath.row].status
tableView.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == table1{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! acntTableViewCell
cell.account.text = account[indexPath.row].email
return cell
}
else if tableView == table2 {
let cell2 = tableView.dequeueReusableCell(withIdentifier: "cell2")
as! popTableViewCell
cell2.pop.text = pop[indexPath.row].answer
return cell2
}
}//its give me error here Missing return in function
I am going to fill two different tables in one viewcontroller. when I return cell it give me error Missing return in function where I am doing wrong can any one suggest me what's wrong with this code
In the first place, you should compare tables using === (references), not ==.
This is one of the cases when an assertion failure is a good way to tell the compiler that no other way of the function exists e.g.:
if tableView === table1 {
return ...
} else if tableView === table2 {
return ...
} else {
fatalError("Invalid table")
}
You can also use a switch:
switch tableView {
case table1:
return ...
case table2:
return ...
default:
fatalError("Invalid table")
}
Both answers are correct, but I believe the best way to do it would be to separate each table view to have its own data source object, not a view controller. Putting multiple tableview data source protocols adds a decent amount of unnecessary code, and if you refactor them into separate objects, you can help avoid a Massive View Controller.
class FirstTableViewDataSource : NSObject, UITableViewDataSource {
var accounts: [ObjectTypeHere]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return accounts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! AcntTableViewCell
cell.account.text = accounts[indexPath.row].email
return cell
}
}
class SecondTableViewDataSource : NSObject, UITableViewDataSource {
var pops: [ObjectTypeHere]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pops.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! PopTableViewCell
cell.account.text = pops[indexPath.row].answer
return cell
}
}
From there, just update the tableviews to pull from these objects
override func viewDidLoad() {
super.viewDidLoad()
self.table1.dataSource = FirstTableViewDataSource()
self.table2.dataSource = SecondTableViewDataSource()
}
The compiler is analyzing what will happen if tableView is neither table1 nor table2. If that should happen, the function will exit with nothing to return.
That's an error.
Your cellForRowAt method should always return a cell, so
Try this way
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == table1{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! acntTableViewCell
cell.account.text = account[indexPath.row].email
return cell
}
//if tableView is not table1 then
let cell2 = tableView.dequeueReusableCell(withIdentifier: "cell2")
as! popTableViewCell
cell2.pop.text = pop[indexPath.row].answer
return cell2
}
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var table1: UITableView!
#IBOutlet weak var table2: UITableView!
let firstClassRef = FirstTableView()
let secondClassRef = SecondTableView()
override func viewDidLoad() {
super.viewDidLoad()
firstClassRef.array1 = ["1","2","3"]
secondClassRef.array2 = ["1","2","3","1","2","3"]
self.table1.dataSource = firstClassRef
self.table2.dataSource = secondClassRef
self.table1.delegate = firstClassRef
self.table2.delegate = secondClassRef
self.table1.reloadData()
self.table2.reloadData()
}
}
class FirstTableView: NSObject, UITableViewDataSource, UITableViewDelegate {
var array1 = Array<Any>()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return array1.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as UITableViewCell
cell.textLabel?.text = array1[indexPath.row] as? String
cell.backgroundColor = UIColor.yellow
return cell
}
}
class SecondTableView: NSObject, UITableViewDataSource, UITableViewDelegate {
var array2 = Array<Any>()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return array2.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as UITableViewCell
cell.textLabel?.text = array2[indexPath.row] as? String
cell.backgroundColor = UIColor.yellow
return cell
}
}
Use Switch Statement
import UIKit
class ViewController: UIViewController , UITableViewDelegate , UITableViewDataSource {
#IBOutlet weak var topTableView: UITableView!
#IBOutlet weak var downTableview: UITableView!
var topData : [String] = []
var downData = [String]()
override func viewDidLoad() {
super.viewDidLoad()
topTableView.delegate = self
downTableview.delegate = self
topTableView.dataSource = self
downTableview.dataSource = self
for index in 0...20 {
topData.append("Top Table Row \(index)")
}
for index in 10...45 {
downData.append("Down Table Row \(index)")
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var numberOfRow = 1
switch tableView {
case topTableView:
numberOfRow = topData.count
case downTableview:
numberOfRow = downData.count
default:
print("Some things Wrong!!")
}
return numberOfRow
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = UITableViewCell()
switch tableView {
case topTableView:
cell = tableView.dequeueReusableCell(withIdentifier: "topCell", for: indexPath)
cell.textLabel?.text = topData[indexPath.row]
cell.backgroundColor = UIColor.green
case downTableview:
cell = tableView.dequeueReusableCell(withIdentifier: "downCell", for: indexPath)
cell.textLabel?.text = downData[indexPath.row]
cell.backgroundColor = UIColor.yellow
default:
print("Some things Wrong!!")
}
return cell
}
}
Im really new to Swift, the question is how can I represent values from array in label.
I want a TableView with cells dynamically represent values from array into the labels which will be created in tableView rows.
import UIKit
import Foundation
class TableViewMarketItemsViewCell: UITableViewController {
var fruits = ["Avocado", "Apricot", "Pomegranate", "Quince"]
var PriceArray = ["1000 тг.","4000 тг.","3000 тг.","2000 тг."]
var categoryArray = ["Green category","Maroon category","Red category","Yellow category"]
// MARK: - UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fruits.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) as! TableViewCell
let fruitName = fruits[indexPath.row]
cell.productTitle.text = fruitName
cell.productImage.image = UIImage(named: fruitName)
return cell
}
}
Thnx in advance
import UIKit
import Foundation
class TableViewMarketItemsViewCell: UITableViewController {
var fruits = ["Avocado", "Apricot", "Pomegranate", "Quince"]
var PriceArray = ["1000 тг.","4000 тг.","3000 тг.","2000 тг."]
var categoryArray = ["Green category","Maroon category","Red category","Yellow category"]
// MARK: - UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fruits.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) as! TableViewCell
let fruitName = fruits[indexPath.row]
cell.productTitle.text = fruitName
cell.productImage.image = UIImage(named: fruitName)
cell.productPrice.text = PriceArray[indexPath.row]
cell.productsubTitle.text = categoryArray[indexPath.row]
return cell
}
}
This helped me.
result in picture below:
img
For inserting data into UITableViewcell use below code:
import UIKit
class ViewController: UIViewController,UITableViewDataSource {
#IBOutlet var tableView: UITableView!
var dataArray:NSArray!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.dataSource = self
dataArray = NSArray(objects: "a","b","c")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = dataArray.object(at: indexPath.row) as? String
return cell
}
}
tableView is outlet of UItableView.
You can populate an UITableView from an array like below:
(assuming that your array has a list of string values):
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Creating the tableView cell
let tableViewCell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath) as! UITableViewCell
//Assigning values
tableViewCell.lblName?.text = array.object(at: indexPath.row) as? String
return tableViewCell
}
In this way you can show the value from your array to the label in your tableView.