I can't print to TableView data with Swift JSON - json

I'm new to using JSON and wanted to start with a simple app to provide an overview of the movie. The following code does not print anything on the tableView, the app remains empty, with no results. He makes no mistakes. In the debug area, however, the data prints them to me. How can I get the results on the tableView?
ViewController.swift
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var popularMoviesArray = [Results]()
var swiftManager = SwiftManager()
var tableViewCell = TableViewCell()
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var labelError: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
swiftManager.delegate = self
swiftManager.fetchUrl()
self.tableView.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return popularMoviesArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
let item = popularMoviesArray[indexPath.row]
cell.labelTitle.text = item.title
cell.labelYear.text = item.release_date
cell.labelRate.text = String(item.vote_average ?? 0.0)
cell.labelOreview.text = item.overview
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "goToDetail", sender: indexPath.row)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard segue.identifier != nil else {
return
}
let letRow = sender as? Int
switch segue.identifier {
case "goToDetail":
(segue.destination as! ViewControllerDetail).itemDetail = popularMoviesArray[letRow!]
default:
return
}
}
}
extension ViewController: SwiftManagerDelegate {
func didUpdateStruct(_ swiftManager: SwiftManager, swiftData: SwiftData) {
DispatchQueue.main.async {
self.popularMoviesArray = swiftData.results
print("PRINT ARRAY - \(self.popularMoviesArray)")
}
}
func didFailWithError(error: Error) {
print(error)
}
}

You have to reload the table view in the delegate method because the data is loaded asynchronously
func didUpdateStruct(_ swiftManager: SwiftManager, swiftData: SwiftData) {
DispatchQueue.main.async {
self.popularMoviesArray = swiftData.results
self.tableView.reloadData()
print("PRINT ARRAY - \(self.popularMoviesArray)")
}
}
Reloading the table view in viewDidLoad is pointless.

Related

how to fix tableview automatic height in swift?

I want to display vertical data collection view in table view cell. but when the data is first reloaded from json the height of the table view doesn't change automatically. but when the tableview is scrolled up, the height of the tableview changes as shown below
This first image appeared when reloading data from Json:
enter image description here
this image when tableview is scrolled up
enter image description here
here is myCode:
view controller
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, reloadTable {
func reloadTableData() {
self.tableView.reloadData()
self.tableView.beginUpdates()
self.tableView.endUpdates()
}
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: Cell.tableView.rawValue)
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 100
tableView.tableFooterView = UIView()
tableView.register(UINib(nibName: "SecondTableViewCell", bundle: nil), forCellReuseIdentifier: "SecondTableViewCell")
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0{
let cell = tableView.dequeueReusableCell(withIdentifier: "SecondTableViewCell", for: indexPath) as! SecondTableViewCell
cell.name.text = "first data"
return cell
}else{
let cell = tableView.dequeueReusableCell(withIdentifier: Cell.tableView.rawValue, for: indexPath) as! TableViewCell
cell.setNeedsLayout()
cell.layoutIfNeeded()
return cell
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0{
return 100
}else {
return UITableView.automaticDimension
}
}
}
here is my tableview cell:
TableViewCell
import UIKit
import Alamofire
import SwiftyJSON
struct dataJSON {
var name: String
}
protocol reloadTable {
func reloadTableData()
}
class TableViewCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
var reload: reloadTable?
var dataJson : [dataJSON] = []
#IBOutlet var collectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
fetchData()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.isScrollEnabled = false
collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: Cell.collView.rawValue)
let collViewLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
collViewLayout.itemSize = UICollectionViewFlowLayout.automaticSize
layoutIfNeeded()
setNeedsLayout()
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataJson.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Cell.collView.rawValue, for: indexPath) as! CollectionViewCell
cell.detail.text = dataJson[indexPath.row].name
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.size.width / 2 - 10, height: 300)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3)
}
func fetchData(){
Alamofire.request("https://jsonplaceholder.typicode.com/users", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON{
(response) in
switch response.result{
case .success(let value):
print(value)
let json = JSON(value)
let name = json["name"].stringValue
print("nameesss: \(name)")
json.array?.forEach({ (item) in
let data = item["name"].stringValue
self.dataJson.append(dataJSON(name: data))
})
self.collectionView.reloadData()
self.reload?.reloadTableData()
case .failure(let error):
print(error)
}
}
}
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
self.collectionView.frame = CGRect(x: 0, y: 0, width: targetSize.width, height: 600)
self.collectionView.layoutIfNeeded()
return self.collectionView.collectionViewLayout.collectionViewContentSize
}
}
Try with
DispatchQueue.main.async { [weak self] in
self?.tableView.reloadData()
}
After inserting data you must update subviews with self.view.layoutSubviews().
Make the delegate and datasource connections from the connection inspector.
Click and drag the outlets from connection inspector to File owner for datasource and delegate.

Show data from JSON in UITableView

....................................................................................................................................................................
I get the data and print it. Maybe the code is not correct I'm just new into swift, but I don't have any errors in Xcode. There's something missing but I just don't know what.
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
struct Class: Codable {
let first_name: String
let last_name: String
let email: String
enum CodingKeys: String, CodingKey {
case first_name = "first_name"
case last_name = "last_name"
case email = "email"
}
}
#IBOutlet weak var tableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://x.de/x.php")
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { print(error!); return }
let decoder = JSONDecoder()
let classes = try! decoder.decode([Class].self, from: data)
for myClass in classes {
print(myClass.first_name)
print(myClass.last_name)
print(myClass.email)
}
}
).resume()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableview.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//return myarray.count
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "groupCell", for: indexPath) as UITableViewCell
return cell
}
}
Several issues
Your view controller is missing dataSource, an Array that holds list of users
Update the array (dataSource) once remote data is received
Reload UITableView once the array (dataSource) changes, using tableView.reloadData()
Within numberOfRowsInSection return the number of array elements dataSource.count
UITableView.dequeueReusableCell(withIdentifier:for:) requires that you register a cell class or xib using tableview.register method
Lastly, instead of underscores, as first_name, use camelCase variable naming convention, as firstName
struct User: Codable {
let firstName: String
let lastName: String
let email: String
enum CodingKeys: String, CodingKey {
case firstName = "first_name"
case lastName = "last_name"
case email = "email"
}
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableview: UITableView!
private var dataSource = [User]() {
didSet {
self.tableview.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableview.register(UITableViewCell.self, forCellReuseIdentifier: "groupCell")
self.tableview.dataSource = self
self.tableview.delegate = self
let url = URL(string: "https://example.com/users.php")
URLSession.shared.dataTask(with: url!, completionHandler: { [weak self] (data, response, error) in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "An error occurred")
return
}
// Within `dataTask` we are on background thread, we must update our UITableView on main thread
DispatchQueue.main.async {
self?.dataSource = try! JSONDecoder().decode([User].self, from: data)
}
}).resume()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableview.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "groupCell", for: indexPath)
let user = self.dataSource[indexPath.row]
cell.textLabel?.text = user.firstName
return cell
}
}
Above code yields
In the cellForRowAt func you have to do something like that :
cell.textLabel?.text = myarray[indexPath.row]
because the text of myarray should be displayed at a label or whatever

Swift 4 saving data from json to an array to show it in TableView

I'm trying to save the data from func getCoinData to an array sympolsCoin and array sympolsCoin to use it in my TableView
I create this class in the same ViewController.swift file :
struct Coin: Decodable {
let symbol : String
let price_usd : String }
And this in my View controller class :
var coins = [Coin]()
var sympolsCoin = [String]()
var priceUSDcoin = [String]()
func getCoinData(completion: #escaping () -> ()) {
let jsonURL = "https://api.coinmarketcap.com/v1/ticker/"
let url = URL(string: jsonURL)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
do {
self.coins = try JSONDecoder().decode([Coin].self, from: data!)
for info in self.coins {
self.sympolsCoin.append(info.symbol)
self.priceUSDcoin.append(info.price_usd)
print("\(self.sympolsCoin) : \(self.priceUSDcoin)")
completion()
}
}
catch {
print("Error is : \n\(error)")
}
}.resume()
}
And when i use the array in my TableView i got blank table !
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BitcoinTableViewCell", for: indexPath) as! BitcoinTableViewCell
cell.coinNameLable.text = sympolsCoin[indexPath.row]
cell.priceLable.text = priceUSDcoin[indexPath.row]
return cell
}
Since you are using JSONDecoder the entire logic to create and populate sympolsCoin and priceUSDcoin is pointless and redundant.
struct Coin: Decodable {
private enum CodingKeys: String, CodingKey {
case symbol, priceUSD = "price_usd"
}
let symbol : String
let priceUSD : String
}
var coins = [Coin]()
The completion handler is redundant, too. Just reload the table view on the main thread after receiving the data:
func getCoinData() {
let jsonURL = "https://api.coinmarketcap.com/v1/ticker/"
let url = URL(string: jsonURL)
URLSession.shared.dataTask(with: url!) { [unowned self] (data, response, error) in
guard let data = data else { return }
do {
self.coins = try JSONDecoder().decode([Coin].self, from: data)
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print("Error is : \n\(error)")
}
}.resume()
}
In viewDidLoad load the data
override func viewDidLoad() {
super.viewDidLoad()
getCoinData()
}
In cellForRow update the UI
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BitcoinTableViewCell", for: indexPath) as! BitcoinTableViewCell
let coin = coins[indexPath.row]
cell.coinNameLable.text = coin.symbol
cell.priceLable.text = coin.priceUSD
return cell
}
Create an Outlet of tableView in ViewController Class and give it name "tableView" then
Try this code: Swift 4
func getCoinData() {
let jsonURL = "https://api.coinmarketcap.com/v1/ticker/"
let url = URL(string: jsonURL)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
do {
self.coins = try JSONDecoder().decode([Coin].self, from: data!)
for info in self.coins {
self.sympolsCoin.append(info.symbol)
self.priceUSDcoin.append(info.price_usd)
print("\(self.sympolsCoin) : \(self.priceUSDcoin)")
self.tableView.reloadData()
}
}
catch {
print("Error is : \n\(error)")
}
}.resume()
}
Call this function in ViewDidLoad like this
override func viewDidLoad() {
super.viewDidLoad()
getCoinData()
}
You need to update the tableView from the main thread. As a good lesson to learn: Always update the UI from the Main Thread. Always.
do {
self.coins = try JSONDecoder().decode([Coin].self, from: data!)
for info in self.coins {
self.sympolsCoin.append(info.symbol)
self.priceUSDcoin.append(info.price_usd)
DispatchQueue.main.async {
self.tableView.reloadData()
}
print("\(self.sympolsCoin) : \(self.priceUSDcoin)")
completion()
}
}
There is, however another problem with your code the way you have your labels setup won't work. TableViewCells get reused so I'm guessing you have #IBOutlets for them somewhere else. What you should do is declare a label constant in cellForRowAt:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
let coinNameLabel = cell.viewWithTag(100) as! UILabel
coinNameLabel.text = sympolsCoin[indexPath.row]
let priceNameLabel = cell.viewWithTag(101) as! UILabel
priceNameLabel.text = priceUSDcoin[indexPath.row]
}
The above code assumes you've setup two labels with the tags 100 and 101 in your storyboard(assuming your using one)
**
// First View Controller
//
//
//
import UIKit
struct Countory : Decodable {
let name: String
let capital: String
let region: String
let alpha2Code: String
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var listArr = [Countory]()
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
let url = "https://restcountries.eu/rest/v2/all"
let urlObj = URL(string: url)!
URLSession.shared.dataTask(with: urlObj) {(data, responds, Error) in
do {
self.listArr = try JSONDecoder().decode([Countory].self, from: data!)
for country in self.listArr {
print("Country",country.name)
print("###################")
print("Capital",country.capital)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
} catch {
print(" not ")
}
}.resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.listArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as! TableViewCell
cell.label1.text = "Name: \(listArr[indexPath.row].name)"
cell.lable2.text = listArr[indexPath.row].capital
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let homeView = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
homeView.res = listArr[indexPath.row].region
homeView.alpha = listArr[indexPath.row].alpha2Code
self.navigationController?.pushViewController(homeView, animated: true)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
}
// SecondViewController
class SecondViewController: UIViewController {
#IBOutlet weak var label4: UILabel!
#IBOutlet weak var label3: UILabel!
var res = ""
var alpha = ""
override func viewDidLoad() {
super.viewDidLoad()
self.label3.text = res
self.label4.text = alpha
}
}
**

Using AlamoFire to fetch data to populate UITableView based on UISearchBar value

Unlike many JSON requests, instead of filtering a long pre-determined JSON, I intend to send a JSON request (using AlamoFire) based on what is typed into a Search Bar, thus fetching the JSON to be parsed (with SwiftyJSON) to fill the UITableView
What I'd like to do is to use the searchTerm (typed into the searchbar) to send an AlamoFire request to Geonames using the searchTerm in the query field of geonames API request. i.e.
http://api.geonames.org/searchJSON?formatted=true&q=(searchTerm)&maxRows=3&username=demo
What I essentially cannot do is send the request AFTER filling out the Search Bar, and therefore populate the table with that data.
Below is my current code (which populates the table upon the view loading with parsed JSON data with a request for "burpham"
import UIKit
import Alamofire
import SwiftyJSON
class SearchAddLocationViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
{
#IBOutlet weak var tblJSON: UITableView!
#IBOutlet weak var searchbarValue: UISearchBar!
weak open var delegate: UISearchBarDelegate?
var arrRes = [[String:AnyObject]]() //Array of dictionary
override func viewDidLoad()
{
super.viewDidLoad()
}
public func searchBarTextDidEndEditing(_ searchBar: UISearchBar) // called when text ends editing
{
callAlamo(searchTerm: searchbarValue.text!)
}
func callAlamo(searchTerm: String)
{
Alamofire.request("http://api.geonames.org/searchJSON?q=\(searchTerm)&maxRows=5&username=garethallenstringer").responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar["geonames"].arrayObject {
self.arrRes = resData as! [[String:AnyObject]]
}
if self.arrRes.count > 0 {
self.tblJSON.reloadData()
}
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "addLocProtoCell")!
var dict = arrRes[indexPath.row]
cell.textLabel?.text = dict["name"] as? String
cell.detailTextLabel?.text = dict["countryName"] as? String
return cell
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return arrRes.count
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You need to listen func searchBarTextDidEndEditing(_ searchBar: UISearchBar) method of UISearchBar delegate for populating your UITableView
class ViewController: UIViewController, UISearchBarDelegate {
#IBOutlet private weak var searchBar: UISearchBar?
override func viewDidLoad() {
super.viewDidLoad()
self.searchBar?.delegate = self
}
//MARK: UISearchBarDelegate methods
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
//You can do your request via Alamofire to populate tableView
}
}
UPDATE #1
import UIKit
import Alamofire
import SwiftyJSON
class SearchAddLocationViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate
{
#IBOutlet weak var tblJSON: UITableView!
#IBOutlet weak var searchbarValue: UISearchBar!
var arrRes = [[String:AnyObject]]() //Array of dictionary
override func viewDidLoad()
{
super.viewDidLoad()
self.searchbarValue.delegate = self
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { // called when text ends editing
{
callAlamo(searchTerm: searchbarValue.text!)
}
func callAlamo(searchTerm: String)
{
Alamofire.request("http://api.geonames.org/searchJSON?q=\(searchTerm)&maxRows=5&username=garethallenstringer").responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar["geonames"].arrayObject {
self.arrRes = resData as! [[String:AnyObject]]
}
if self.arrRes.count > 0 {
self.tblJSON.reloadData()
}
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "addLocProtoCell")!
var dict = arrRes[indexPath.row]
cell.textLabel?.text = dict["name"] as? String
cell.detailTextLabel?.text = dict["countryName"] as? String
return cell
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return arrRes.count
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Parsing JSON into TableView xcode 6.0.1, iOS8

There seems to be a dozen different ways to do this. This is the leanest I've come with, but am getting blank cells. So close!
MY holy grail next is to grab this all into a custom cell, my first steps here.
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var names = []
#IBOutlet var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string:"http://MYURL-here-which-pulls-down-the-JSON.json")
let JSONData = NSData(contentsOfURL: url)
var err: NSError?
let JSONResult = NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: nil) as NSArray
var _names: NSMutableArray = NSMutableArray()
for item: AnyObject in JSONResult {
let name: NSString = item["name"] as NSString
_names.addObject(name)
}
self.names = _names
println(self.names)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
// THIS LINE IS THE ONE ***************************************************
// NO VALUE TO DISPLAY ****************************************************
cell.textLabel?.text = names[indexPath.row]
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
The problem is that you are creating the cell yourself. You shouldn't do that.
Create a cell in the table view with a reuse identifier in Interface Builder and set the Cell Style to Basic. Then you can use code like this:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier",
indexPath: indexPath) as UITableViewCell
cell.textLabel?.text = names[indexPath.row]
return cell
}