I would like to show all the values of this loop in the tableview. The code is to calculate an Amortization Table for loans. I tried saving the data of the loop in the array, but it always gives me the last values. I really got stuck on this. So how can I do that, please? This is my code:
import UIKit
class tableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var tableView: UITableView!
var arr = [Int]()
var cell:tableCell!
var TPayment: float_t! // calls value of 59600 from main controller
var years1: float_t! // number of months = 180 ( 15 years)
var monthlyPayment: float_t! // 471
var interest: float_t! // 5%
var principil: float_t! //222
var interestrate: float_t! // 249
var initil: float_t!
var data = Array<float_t>()
var data2: NSMutableArray = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
let c = Int(years1)
arr += 0...c
tableCalculation()
// Register custom cell
let nib = UINib(nibName: "table", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "cell")
}
func tableCalculation() {
let years = Int(years1)
initil = TPayment - 0
for i in 0..<years {
initil = initil - principil
interest = initil * interestrate
principil = monthlyPayment - interest
print("Month : \(monthlyPayment), principil: \(principil),interest: \(interest), initi: \(initil)")
data = [interest]
self.data2 = [initil]
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! tableCell
cell.lbl1.text = "\(arr[indexPath.row])"
cell.lbl2.text = "\(monthlyPayment)"
cell.lbl3.text = "\(data[indexPath.row % data.count])"
cell.lbl4.text = "\(principal)"
cell.lbl5.text = "\(self.data2[indexPath.section])"
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("Row \(indexPath.row) selected")
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 40
}
}
Table View with UITableView
Table view with print()
The main issue is with your data array.
In your loop where you populate your data array, in tableCalculation, there's this:
data = [interest]
It means that for each iteration you set the data array to [interest] instead of appending the new item to the array.
What you should do instead:
data.append(interest)
Note that you make the same mistake with self.data2. But now you know how to fix this kind of error.
In the cellForRowAtIndexPath method you are giving the same data to print that looks like the issue
I don't get much for all the labels but you can change it based on the requirement
for lbl2 and lbl4 you are passing a same single float variable for all the rows that's why it show the same value, if you want to show the different value for each row you should store it in array and at cellForRowAtIndexPath get it like you are doing for lbl1
cell.lbl2.text = currencyFormatter(monthlyPayment)
cell.lbl4.text = currencyFormatter(principil)
for lbl5 Your code cell code should be like this
cell.lbl5.text = "\(self.data2[indexPath.row])"
For the lbl 3 & lbl 5 when i execute this code with static value to get interest it only stores one value in the array
for i in 0..<years {
let interest = 5.0 * 4.0
data = [interest]
}
to store every value you calculated in array you should use append
data.append(interest)
self.data2.append(initil)
as there is only 1 value in the array for every index path it gives 0th value in the array as per your modulo operation so it shows same value in each row
Related
I have a data source in this form:
struct Country {
let name: String
}
The other properties won't come into play in this stage so let's keep it simple.
I have separated ViewController and TableViewDataSource in two separate files. Here is the Data source code:
class CountryDataSource: NSObject, UITableViewDataSource {
var countries = [Country]()
var filteredCountries = [Country]()
var dataChanged: (() -> Void)?
var tableView: UITableView!
let searchController = UISearchController(searchResultsController: nil)
var filterText: String? {
didSet {
filteredCountries = countries.matching(filterText)
self.dataChanged?()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredCountries.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let country: Country
country = filteredCountries[indexPath.row]
cell.textLabel?.text = country.name
return cell
}
}
As you can see there is already a filtering mechanism in place.
Here is the most relevant part of the view controller:
class ViewController: UITableViewController, URLSessionDataDelegate {
let dataSource = CountryDataSource()
override func viewDidLoad() {
super.viewDidLoad()
dataSource.tableView = self.tableView
dataSource.dataChanged = { [weak self] in
self?.tableView.reloadData()
}
tableView.dataSource = dataSource
// Setup the Search Controller
dataSource.searchController.searchResultsUpdater = self
dataSource.searchController.obscuresBackgroundDuringPresentation = false
dataSource.searchController.searchBar.placeholder = "Search countries..."
navigationItem.searchController = dataSource.searchController
definesPresentationContext = true
performSelector(inBackground: #selector(loadCountries), with: nil)
}
The loadCountries is what fetches the JSON and load the table view inside the dataSource.countries and dataSource.filteredCountries array.
Now, how can I get the indexed collation like the Contacts app has without breaking all this?
I tried several tutorials, no one worked because they were needing a class data model or everything inside the view controller.
All solutions tried either crash (worst case) or don't load the correct data or don't recognise it...
Please I need some help here.
Thank you
I recommend you to work with CellViewModels instead of model data.
Steps:
1) Create an array per word with your cell view models sorted alphabetically. If you have data for A, C, F, L, Y and Z you are going to have 6 arrays with cell view models. I'm going to call them as "sectionArray".
2) Create another array and add the sectionArrays sorted alphabetically, the "cellModelsData". So, The cellModelsData is an array of sectionArrays.
3) On numberOfSections return the count of cellModelsData.
4) On numberOfRowsInSection get the sectionArray inside the cellModelsData according to the section number (cellModelsData[section]) and return the count of that sectionArray.
5) On cellForRowAtindexPath get the sectionArray (cellModelsData[indexPath.section]) and then get the "cellModel" (sectionArray[indexPath.row]). Dequeue the cell and set the cell model to the cell.
I think that this approach should resolve your problem.
I made a sample project in BitBucket that could help you: https://bitbucket.org/gastonmontes/reutilizablecellssampleproject
Example:
You have the following words:
Does.
Any.
Visa.
Count.
Refused.
Add.
Country.
1)
SectionArrayA: [Add, Any]
SectionArrayC: [Count, Country]
SectionArrayR: [Refused]
SectionArrayV: [Visa]
2)
cellModelsData = [ [SectionArrayA], [SectionArrayC], [SectionArrayR], [SectionArrayV] ]
3)
func numberOfSections(in tableView: UITableView) -> Int {
return self.cellModelsData.count
}
4)
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionModels = self.cellModelsData[section]
return sectionModels.count
}
5)
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let sectionModels = self.cellModelsData[indexPath.section]
let cellModel = sectionModels[indexPath.row]
let cell = self.sampleCellsTableView.dequeueReusableCell(withIdentifier: "YourCellIdentifier",
for: indexPath) as! YourCell
cell.cellSetModel(cellModel)
return cell
}
First and foremost, I apologize if my title is kind of misleading compared to my question; I wasn't really sure how to word it out. Hopefully my pictures do more explanation than me. Im still at the beginning stages of iOS development and I seem to have run into my first problem. Basically, I'm creating an app where a person can input item's they have purchased and then later on sold and they can keep track of their profits/losses.
Basically, a user can add an item like the image below and it will then proceed to populate the tableview with the item title, how much they gained or lost through that transaction, and other pieces of information about that item
Pic 1
Second, I have a feature where a user can delete an item from the cell by swiping left. My first problem is that the quantity (I.e 3) and total amount ("$169.82") labels don't update instantly after the deletion of the cell. My second problem is the total amount label itself; I'm able to update the quantity label by simply retrieving the count of the array where the Items Objects are stored in but I'm unable to do so with the total amount label
Pic 2
Pic 3
Here is a snippet of my code
import UIKit
var ClothesList = [String]()
var ClothesResults = [String]()
var ClothesTotalQty = AccessoryList.count
var ClothesBuy = [String]()
var ClothesSell = [String]()
var ClothesFeeArray = [String]()
var ClothesSize = [String]()
var ClothesTotalAmount = 0.0
class ViewClothes: UIViewController, UITableViewDelegate,
UITableViewDataSource {
// MARK: Outlets
#IBOutlet weak var ClothesQuantity: UILabel!
#IBOutlet weak var ClothesAmount: UILabel!
#IBOutlet weak var ClothesNames: UITableView!
// MARK: Functions
func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
return ClothesList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
let list = ClothesNames.dequeueReusableCell(withIdentifier:
"Clothes") as! CustomCells
list.NameLabel?.text = ClothesList[indexPath.row]
list.BuyPriceLabel?.text = "Buy Price: $\
(ClothesBuy[indexPath.row])"
list.FeeLabel?.text = "Fee: \(ClothesFeeArray[indexPath.row])%"
list.SizeLabel?.text = "Size: \(ClothesSize[indexPath.row])"
list.SellLabel?.text = "Sell Price: $\
(ClothesSell[indexPath.row])"
list.ModifiedProfitLabel?.text = ClothesResults[indexPath.row]
return list
}
func tableView(_ tableView: UITableView, commit editingStyle:
UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if(editingStyle==UITableViewCellEditingStyle.delete){
ClothesList.remove(at: indexPath.row)
And here is my attempt at the solution:
/* My Attempt at subtracting the removed cell from the total
amount
let placeholder = ClothesResults[indexPath.row]
ClothesTotalAmount = ClothesTotalAmount - Double(placeholder)!
ClothesResults.remove(at: indexPath.row) */
ClothesTotalQty = ClothesList.count
ClothesNames.reloadData()
}
}
Rest of the code
override func viewDidAppear(_ animated: Bool) {
ClothesNames.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.shadowImage = UIImage()
ClothesNames.delegate = self
ClothesNames.dataSource = self
ClothesQuantity.text = String(ClothesTotalQty)
let totalAmount = ClothesTotalAmount as NSNumber
let totalString = currencyFormatter.string(from: totalAmount)
ClothesAmount.text = totalString
As #Kamran said . You need to recalculate after deleting cell
func tableView(_ tableView: UITableView, commit editingStyle:
UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if(editingStyle==UITableViewCellEditingStyle.delete){
ClothesList.remove(at: indexPath.row)
ClothesQuantity.text = String(ClothesTotalQty)
let totalAmount = ClothesTotalAmount as NSNumber
let totalString = currencyFormatter.string(from: totalAmount)
ClothesAmount.text = totalString
ClothesTotalQty = ClothesList.count
ClothesNames.reloadData()
}
}
simply create a method. In which you have to calculate the total amount and count of clothes from your manged array . And call the function each time you modify the list.
if(editingStyle==UITableViewCellEditingStyle.delete){ RECALCULATE YOUR AMOUNT AND CLOTHES COUNT HERE OR CALL A FUNCTION FOR SAME ClothesNames.reloadData() } }
Before anyone suggests to pull the Firebase data from within the PlayerController's viewWillAppear, I already know how to do that and if I did it that way I know how to pass the data to the ScoreController. In this situation I need to pull the data directly from within the cell and somehow pass the data back from there.
I have a tableView inside a PlayerController that displays the randomPower, name, and score of each player. Inside the tableView's cell I pull the name and score from Firebase using a function getScoreDataFromFirebase(). The function is located directly inside the tableView's PlayerCell and once I get the values from Firebase I initialize the cell's name and score outlets right then and there.
Inside the tableView's cellForRowAtIndexPath I call cell.getScoreDataFromFirebase() and everything works fine because both outlets display the correct values.
From that point on I have a ScoreController. When a tableView cell is chosen the score is sent to the ScoreController.
The problem is since I'm pulling the data directly from within the cell itself the only way I could pass the score (pulled from Firebase) to ScoreController was to 1st set a didSet score property inside the cell.
Still inside the cell when I pull the score data from Firebase 2nd I initialize the score property with it
3rd inside the tableView's cellForAtIndexPath I use an if let to pass the value from the cell's score property to the the tableData.
When I first try to send the indexPath of that tableData over to the ScoreController sometimes it's nil even though the cell's score property definitely has a value (I used to break points to check). If I select any of the very first few tableView cells that are visible they will have a nil value for the score property. However if I scroll further down through the cells and back up then those same cells will no longer have a nil score property.
What I found out was the if let statement was running before the Firebase code was pulled so the score property was nil for first few cells that are on scene. The odd thing is everything works fine once I start scrolling.
How can I pass a value pulled directly from a cell to the tableView's didSelectRow?
PlayerModel:
class PlayerModel{
name:String?
score:String?
randomPower:String?
}
TableViewCell SubClass:
class PlayerCell:UITableViewCell{
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var scoreLabel: UILabel!
#IBOutlet weak var randomPowerLabel: UILabel!
internal var score: String?{
didSet{
print("**********\(score ?? "*********")")
}
}
override func prepareForReuse() {
super.prepareForReuse()
nameLabel.text = " "
scoreLabel.text = " "
}
func getScoreDataFromFirebase(){
let scoreRef = usersRef?.child("score")
scoreRef?.observe( .value, with: {
(snapshot) in
for child in snapshot.children{
let user = child as! DataSnapshot
for player in user.children{
let eachPlayer = player as! DataSnapshot
if let dict = eachPlayer.value as? [String:Any]{
let name = dict["name"] as? String ?? " "
let score = dict["score"] as? String ?? " "
self.nameLabel.text = name
self.scoreLabel.text = score
self.score = score
}
}
}
}
}
}
TableView:
class PlayerController: UITableViewDataSource, UITableViewDelegate{
#IBOutlet weak fileprivate var tableView: UITableView!
var players = [PlayerModel]() // this array is populated with data from a previous vc. The number of players in the array are the same exact number of players that's pulled from the getScoreDataFromFirebase() function
override func viewDidLoad() {
super.viewDidLoad()
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return players.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PlayerCell", for: indexPath) as! PlayerCell
let cellData = players[indexPath.row]
cellData.randomPowerLabel.text = cellData.power
cell.getScoreDataFromFirebase()
if let score = cell.score{
cellData.score = score
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let indexPath = tableView.indexPathForSelectedRow else { return }
let scoreVC = storyboard?.instantiateViewController(withIdentifier: "ScoreController") as! ScoreController
scoreVC.score = players[indexPath.row].score
}
You can achieve this using delegation :
Create a protocol
protocol UpdateValueDelegate: class {
func changeValue(score: String, row: Int)
}
Your UIViewController should look like this :
PlayController : UITableViewDataSource, UITableViewDelegate, UpdateValueDelegate
{
var scoreDict:[String:String] = [:]
//
//
func changeValue(score: String, row: Int)
{
self.scoreDict["\(row)"] = score
}
}
In cellForRowAtIndexPath set cell.delegate = self and cell.row = indexPath.row
Your UITableViewCell should look like this :
class PlayerCell:UITableViewCell: UITableViewCell
{
weak var delegate: UpdateValueDelegate?
var row: Int?
//
//
}
Finally pass score from getScoreDataFromFirebase by calling delegate function:
func getScoreDataFromFirebase()
{
//
//
delegate. changeValue(score: localScore, row: self.row)
}
Now you have the value in your viewController from where it can be easily passed to didSelectRow using the global dictionary ** scoreDict**.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
var score = self.scoreDict["\(indexPath.row)"]
// Use score
}
I have implemented a tableView using PLIST to set properties.
I would like to add three sections at specific row. (row 12, row24, row 35)
I have tried with following code but it will be too much code and not working well.
Images and code are added below.
import UIKit
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tblStoryList: UITableView!
var array = PLIST.shared.mainArray
var array = PLIST.shared.mainArray
let sections: [String] = ["First stage","Second Stage","Third Stage"]
let s1Data : [String] = ["Row1","Row2","Row3"]
let s2Data : [String] = ["Row4","Row5","Row6"]
let s3Data : [String] = ["Row7","Row8","Row9"]
var sectionData: [Int: [String]] = [:]
override func viewDidLoad() {
super.viewDidLoad()
sectionData = [0: s1Data, 1: s2Data, 2: s3Data]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (sectionData[section]?.count)!
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "StoryTableviewCell", for: indexPath) as! StoryTableviewCell
//making plist file
let dict = self.array[indexPath.row]
let title = dict["title"] as! String
let imageName = dict["image"] as! String
let temp = dict["phrases"] as! [String:Any]
let arr = temp["array"] as! [[String:Any]]
let detail = "progress \(arr.count)/\(arr.count)"
//property to plist file
cell.imgIcon.image = UIImage.init(named: imageName)
cell.lblTitle.text = title
cell.lblSubtitle.text = detail
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
}
The indexPath.row you are getting in the tableView's cellForRowAt is relative to the section. You cannot use it directly as the index of your main array (which has all the rows).
You will need to perform a simple calculation to convert the indexPath.row to an index of that array (by offsetting the row with the total item count of previous sections) :
let index = [0,12,36][indexPath.section] + indexPath.row
let dict = array[index]
The same thing applies to the response you give to numberOfRowsInSection:
return [12,24,35][section]
I find it a bit odd that the data structure (PLIST) would be so rigid that it always contains exactly those number of entries and will never change. I would suggest a more generalized approach if only to avoid spreading hard coded numbers (e.g. 12,24,35,36) all over the place.
for example:
// declare section attributes in your class
let sectionTitles = ["First stage","Second Stage","Third Stage"]
let sectionSizes = [12,24,35] // central definition, easier to maintain (or adjust to the data)
let sectionOffsets = sectionSizes.reduce([0]){$0 + [$0.last!+$1] }
// and use them to respond to the table view delegate ...
let index = sectionOffsets[indexPath.section] + indexPath.row
let dict = array[index]
// ...
return sectionSizes[section] // numberOfRowsInSection
Using this approach, you shouldn't need to create sectionData (unless you're using it for other purposes elsewhere).
BTW, in your sample code, the sectionData content is hard coded with data that is not consistent with the expected section sizes so it would not work even with a correct index calculation.
you can try to use switch case in tableView:cellForRowAtIndexPath:
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I would like to loop my numbers into the uitableviewcell and printing all the values from the highest number to the lowest and printing them in each cell. I posted the full code. See the cell.text output. This is my code:
import UIKit
class tableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var tableView: UITableView!
var arr = [Int]()
var cell:tableCell!
var Payment: float_t! = 59600
var years1: float_t! = //15 * 12 = 180
var monthlyPayment: float_t! = 471
var interest: float_t! = 5%
var principal: float_t! = 222
var interstate: float_t! = 249
var initil: float_t!
var data = Array<float_t>()
var data2: NSMutableArray = []
override func viewDidLoad() {
super.viewDidLoad()
let c = Int(years1)
arr += 0...c
tableCalculation()
let nib = UINib(nibName: "table", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "cell")
}
func tableCalculation() {
let years = Int(years1)
initil = TPayment - 0
for i in 0..<years {
initil = initil - principil
interest = initil * interestrate
principil = monthlyPayment - interest
print("Month : \(monthlyPayment), principil: \(principil),interest: \(interest), initi: \(initil)")
self.data2 = [initil]
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! tableCell
cell.lbl1.text = "\(arr[indexPath.row])"
cell.lbl2.text = currencyFormatter(monthlyPayment)
cell.lbl3.text = currencyFormatter(interest)
cell.lbl4.text = currencyFormatter(principil)
cell.lbl5.text = "\(self.data2[indexPath.row % data2.count])"
return cell
}
// 4
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("Row \(indexPath.row) selected")
}
// 5
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 70
}
func currencyFormatter(Price: float_t) ->String {
let currencyFormatter = NSNumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
// localize to your grouping and decimal separator
let numberOfPlaces: float_t = 1.0
let multiplier: float_t = pow(10.0, numberOfPlaces)
let num = Price
let rounded = round(num * multiplier) / multiplier
let priceString = currencyFormatter.stringFromNumber(rounded)
return priceString!
}
}
This code always gives me the last number of the loop for all values, I would like to change it to write from the first value to the last one in every cell.
Welcome to SO. Neither your question nor your code make any sense.
It looks to me like you have no idea how to use table views.
You need to set up a data model (usually an array) that holds the data for your table view. Then when your cellForRowAtIndexPath method gets called, you look at the row (or row and section) in the request, fetch the data for that row (or row & section for a sectioned table view) and use that data to configure a cell which you return.
Try it this way:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! tableCell
cell.lbl5.text = "\(initial - indexPath.row*225)" //subtracts each consecutive row by a higher multiple of 225.
return cell
}
You need to understand that cellForRow:atIndexPath is a UITableView datasource method that's called by the UIKit framework. It gets called when the tableview is loaded, based on the number of sections (specified by another datasource method), and the number of rows in each section (also specified by yet another datasource method).
Here's how table views work, like Duncan said you need to know.
/*We need to subclass UITableViewDataSource and UITableViewDelegate
so we gain access to tableView methods. Don't forget to link your
tableView in the storyboard to the delegate and datasource!*/
class controller: UIViewController, UITableViewDataSource, UITableViewDelegate {
//1: Model. All the data you're gonna use for your table view
var data = Array<String>()
override func viewDidLoad() {
//1: Populate model with some data when the view loads.
self.data = ["Oranges", "Apples", "Bananas", "Grapes"]
}
//2: Number of rows in table view. This determines how many times #3 is called (below).
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//We want the table view to have all the items in variable `data`. So, we need to have as many cells as the number of items in `data`
return data.count
}
//3: This is called for each cell. It lets you customise each cell how you want.
//For us, we'll make the text inside the cell the current item in the `data` array
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//Get the cell from the tableView. Use the identifier you've specified in the storyboard.
let cell = tableView.dequeueReusableCellWithIdentifier("myCellIdentifier", forIndexPath: indexPath)
//Set the text as the current item in `data`
cell.textLabel?.text = data[indexPath.row]
//Use this cell we've just created for the current row
return cell
}
}