Reputation: 159
I am populating a UITableView with the following code in swift. Unfortunately it is show a blank tableview not sure what I am doing wrong.
class MasterTableViewController: UITableViewController
{
var cities: [City]?
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
let london = City(name: "London", coordinates: (51.50722, -0.12750))
let melbourne = City(name: "Melbourne", coordinates: (-37.8136, 144.9631))
let singapore = City(name: "Singapore", coordinates: (-23.5475000,-46.6361100))
let saopaulo = City(name: "Sao Paulo", coordinates: (49.3297,8.57428))
let nurbergring = City(name: "Nurbergring", coordinates: (45.58005,9.27246))
cities?.append(london)
cities?.append(melbourne)
cities?.append(singapore)
cities?.append(saopaulo)
cities?.append(nurbergring)
// Do any additional setup after loading the view, typically from a nib.
}
Upvotes: 0
Views: 135
Reputation: 71
Have you checked that the cell reuse identifier is correctly named on the storyboard?
Upvotes: 0
Reputation: 2120
var cities: [City]?
This line means that you declare cities
as optional array, that is, it can be nil
value. Because cities
is only declared and not initialized at this point, its value is nil
.
After that, in viewDidLoad
, you create an City
object and try to add it to cities
array, but it will not be added, because cities
has a nil
value. You need initialize it first:
override func viewDidLoad()
{
super.viewDidLoad()
cities = [] // initialize as an empty array
let london = City(name: "London", coordinates: (51.50722, -0.12750))
// ...
cities?.append(london)
// ...
}
Upvotes: 1
Reputation: 2643
You need to implement the UITableView delegate methods. Here's what you should do :
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cities.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell=tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell
cell.textLabel.text= cities[indexPath.row].name //Or add others here
return cell
}
Here are some tutorials you should check out, which will brush up your iOS skills. And also note that the first method is optional, but it's a good practice to implement it.
Upvotes: 0