Reputation: 113
I have a bunch of arrays:
let CNSNRT = ["CNS", "NRT", 3637, 2113] as [Any]
let ADKANC = ["ADK", "ANC", 1192, 2200] as [Any]
let LAXMCE = ["LAX", "MCE", 259 , 2370] as [Any]
let ANCMCG = ["ANC", "MCG", 219, 2440] as [Any]
let ATLGLH = ["ATL", "GLH", 378, 2590] as [Any]
let CNSHKG = ["CNS", "HKG", 3450, 2728] as [Any]
let AKPFAI = ["AKP", "FAI", 253, 2960] as [Any]
let ADLKUL = ["ADL", "KUL", 3524, 2984] as [Any]
That get combined:
let routesArray = [CNSNRT, ADKANC, LAXMCE, ANCMCG, ATLGLH, CNSHKG, AKPFAI, ADLKUL]
With print(routesArray[0])
I get ["CNS", "NRT", 3637, 2113]
and with print(routesArray[0][0]
I get CNS
, so everthing appears to be referencing correctly.
However, I can't figure out how to get this into a UITableView
correctly. Basically, each item in routesArray
should be a cell, and the items within the arrays will define the labels in the cells.
Current code:
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var routesTableView: UITableView!
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return routesArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = routesTableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier")!
let text = "\(routesArray[indexPath.row])"
cell.textLabel?.text = text
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
routesTableView.dataSource = self
}
Yields a table with lines that look like ["CNS", "NRT", 3637, 2113]
but I can't figure out how to break those down to apply them to specific labels on the cell. So for example originLabel
should display CNS
but in the next cell, originLabel
should display ADK
.
Upvotes: 4
Views: 1173
Reputation: 318824
At the moment you access a given array and convert it a single string using:
let text = "\(routesArray[indexPath.row])"
Since you just want the first element of the error in the originLabel
of the cell, you need to get that first element.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = routesTableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier")!
let rowData = routesArray[indexPath.row]
if let firstStr = rowData.first as? String {
cell.originLabel = firstStr
}
return cell
}
FYI - you should not be force-unwrapping the call to dequeueReusableCell
. It can return nil
and your app will crash.
Upvotes: 2