XCode 12/Swift 4 Custom Cells not displaying on UI Table Cell View - swift

Ok so, I am trying to make a custom table that has a news feed from newsapi, from my debugging: the api calls and such get made and the data is acessed, its just that it doesnt display on the table, it shows up as a blank table.
Here is the code:
This is from the "first view controller" as I am using the tabbed template
import UIKit
class FirstViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var articles: [Article]? = []
override func viewDidLoad() {
super.viewDidLoad()
fetchArticles()
}
func fetchArticles(){
let urlRequest = URLRequest(url: URL(string: "https://newsapi.org/v2/top-headlines?country=us&?category=business&apiKey=sorrynotgivingmykey")!)
let task = URLSession.shared.dataTask(with: urlRequest){(data,response,error) in
if error != nil{
print(error)
return
}
self.articles = [Article]()
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]
if let articlesFromJson = json["articles"] as? [[String: AnyObject]]{
for articlesFromJson in articlesFromJson{
let article = Article()
if let title = articlesFromJson["title"] as? String, let desc = articlesFromJson["description"] as? String, let url = articlesFromJson["url"] as? String, let imageToUrl = articlesFromJson["urlToImage"] as? String, let date = articlesFromJson["publishedAt"] as? String{
article.headline = title
article.desc = desc
article.url = url
article.imageUrl = imageToUrl
article.date = date
// print(article.date)
// print(article.headline)
}
self.articles?.append(article)
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}catch let error{
print(error)
}
}
task.resume()
// print(articles)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.articles!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "worklmao", for: indexPath) as! ArticleCell
cell.title.text = self.articles?[indexPath.item].headline
cell.desc.text = self.articles?[indexPath.item].desc
cell.date.text = self.articles?[indexPath.item].date
print("lol lmao hahax help fuck shit")
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
1
}
}
And this is the cell classes I used for the articles
import UIKit
class ArticleCell: UITableViewCell {
#IBOutlet weak var date: UILabel!
#IBOutlet weak var desc: UILabel!
#IBOutlet weak var title: UILabel!
#IBOutlet weak var ImgView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
This is the article class
import UIKit
class Article: NSObject {
var headline: String?
var desc: String?
var url: String?
var date: String?
var imageUrl: String?
}
and bare in mind I did setup the class for the cell properly(at least I think
Still, this is what I get:

Don't forget to connect dataSource and delegate for tableView.
Change your tableView outlets to this:
#IBOutlet weak var tableView: UITableView! {
didSet {
tableView.delegate = self
tableView.dataSource = self
}
}
Some points:
You don't have to declare articles array as optional. Simply do this :
var articles = [Article]()
Try to learn about codables for JSON parsing.

Related

How to prevent cells from mirroring button pressed action in another cell? Part #2

This would be part # 2 of my question How to prevent cells from mirroring button pressed action in another cell?
What im trying to do is have my buttons have a button pressed turn red while a previously selected button deselects to back to blue, and also preventing it from mirroring the pressed button action in another cell, I have achieved that in a previous question I posted
what Im trying to do is integrate this with classes that pass data from Firebase Firestore. since I don't know where to go to convert this prevent the cells from mirroring the same button select action in another and changes the button selected to red and automatically deselects previous button back to blue
I have been stuck trying to make this work and just not getting the right luck to make it happen, I have been getting error codes in 3 different areas in ViewController preventing my code from compiling and making it work so that it works with my cells that pass data to labels from my cloud Firestore
any help would be appreciated and thank you for your time
import Foundation
import UIKit
class Labels {
var id: String
var lbl1: String
var lbl2: String
var lbl3: String
init(id: String,
lbl1: String,
lbl2: String,
lbl3: String) {
self.id = id
self. lbl1 = lbl1
self. lbl2 = lbl2
self. lbl3 = lbl3
}
convenience init(dictionary: [String : Any]) {
let id = dictionary["id"] as? String ?? ""
let lbl1 = dictionary["lbl1"] as? String ?? ""
let lbl2 = dictionary["lbl2"] as? String ?? ""
let lbl3 = dictionary["lbl3"] as? String ?? ""
self.init(id: id,
lbl1: lbl1,
lbl2: lbl2,
lbl3: lbl3)
}
}
enum ButtonSelectionIdentity {
case first
case second
case third
}
struct CellModel {
let buttonSelectionIdentity: ButtonSelectionIdentity
let labels: Labels
}
import UIKit
import SDWebImage
import Firebase
protocol OptionSelectDelegate: class {
func onCellModelChange(cell: Cell, model: ButtonSelectionIdentity)
}
class Cell: UITableViewCell {
weak var labels: Labels!
private var elements: [ButtonSelectionIdentity] = []
weak var optionSelectDelegate: OptionSelectDelegate?
#IBOutlet weak var lbl1: UILabel!
#IBOutlet weak var lbl2: UILabel!
#IBOutlet weak var lbl3: UILabel!
#IBOutlet weak var btnOne: RoundButton!
#IBOutlet weak var btnTwo: RoundButton!
#IBOutlet weak var btnThree: RoundButton!
func configure(withLabels labels: Labels) {
lbl1.text = labels.lbl1
lbl2.text = labels.lbl2
lbl3.text = labels.lbl3
}
override func layoutSubviews() {
super.layoutSubviews()
}
func update(with model: ButtonSelectionIdentity) {
btnOne.backgroundColor = UIColor.blue
btnTwo.backgroundColor = UIColor.blue
btnThree.backgroundColor = UIColor.blue
switch model {
case .first:
btnOne.backgroundColor = UIColor.red
case .second:
btnTwo.backgroundColor = UIColor.red
case .third:
btnThree.backgroundColor = UIColor.red
}
}
#IBAction func optionSelectOne(_ sender: RoundButton!) {
optionSelectDelegate?.onCellModelChange(cell: self, model: .first)
}
#IBAction func optionSelectTwo(_ sender: RoundButton!) {
optionSelectDelegate?.onCellModelChange(cell: self, model: .second)
}
#IBAction func optionSelectThree(_ sender: RoundButton!) {
optionSelectDelegate?.onCellModelChange(cell: self, model: .third)
}
}
import UIKit
import Firebase
import FirebaseFirestore
class ViewController: UIViewController {
private var elements: [CellModel] = []
#IBOutlet weak var tableView: UITableView!
var labelSetup: [Labels] = []
override func viewDidLoad() {
super.viewDidLoad()
//▼ Cannot convert value of type 'ButtonSelectionIdentity' to expected argument type 'CellModel'
elements.append(ButtonSelectionIdentity.first) // error one
tableView.dataSource = self
tableView.delegate = self
fetchLabels { (labels) in
self.labelSetup = labels.sorted(by:
self.tableView.reloadData()
}
}
func fetchLabels(_ completion: #escaping ([Labels]) -> Void) {
let ref = Firestore.firestore().collection("labels")
ref.addSnapshotListener { (snapshot, error) in
guard error == nil, let snapshot = snapshot, !snapshot.isEmpty else {
return
}
completion(snapshot.documents.compactMap( {Labels(dictionary: $0.data())} ))
}
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return labelSetup.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? Cell else { return UITableViewCell() }
cell.configure(withLabels: labelSetup[indexPath.row])
cell.optionSelectDelegate = self
let model = elements[indexPath.row]
//▼ Cannot convert value of type 'CellModel' to expected argument type 'ButtonSelectionIdentity'
cell.update (with: CellModel) //error 2
return cell
}
}
extension ViewController: OptionSelectDelegate {
func onCellModelChange(cell: Cell, model: ButtonSelectionIdentity) {
guard let indexPath = productListTableView.indexPath(for: cell) else {
return
}
let index = indexPath.row
elements[index] = model
//▼ Cannot assign value of type 'ButtonSelectionIdentity' to type 'CellModel'
cell.update(with: model) //error 3
}
}

"Fatal error: Index out of range 2019-08-30 11:01:35.001667-0400 fmcBeta[58563:3478851] Fatal error: Index out of range"

I am creating an events feed, using a table view and Firebase as my database. I am using dateformatter with a style type of full for date and short for time and writing it to my database as a string which is perfect, it writes exactly how i want it to.
However, when i try to read the data from firebase and display it on my textlabel in the tableview cell i get the following error.
Error:
"Fatal error: Index out of range
2019-08-30 11:01:35.001667-0400 fmcBeta[58563:3478851] Fatal error: Index out of range"
Any help would be greatly appreciated i am self learning and fairly new to swift.
This is my table view cell:
class EventsTableViewCell: UITableViewCell {
#IBOutlet weak var eventLocation: UILabel!
#IBOutlet weak var eventDate: UILabel!
#IBOutlet weak var eventTitle: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
This is my viewcontoller with tableview protocols:
class EventsViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var eventsRef: DatabaseReference?
var eventsDatabaseHandle:DatabaseHandle?
var eventsTitles = [String]()
var eventTimestamps:[String] = []
var eventsLocations = [String]()
eventsRef = Database.database().reference()
tableView.reloadData()
tableView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi)
tableView.delegate = self
tableView.dataSource = self
eventsDatabaseHandle = eventsRef?.child("Church Events").observe(.childAdded, with: { (snaphot) in
let eventPost = snaphot.value as! [String: Any]
self.eventTimestamps.append(eventPost["eventdate"] as! String)
self.eventsTitles.append(eventPost["eventtitle"] as! String)
self.eventsLocations.append(eventPost["eventlocation"] as! String)
self.tableView.reloadData()
})
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return eventsTitles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "events") as! EventsTableViewCell
cell.eventTitle.text! = eventsTitles[indexPath.row]
cell.eventDate.text! = eventTimestamps[indexPath.row]
cell.eventLocation.text! = eventsLocations[indexPath.row]
cell.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
return cell
}
}
This is how i'm writing the data to Firebase
#IBAction func saveEventsButton(_ sender: Any) {
let eventsDates = DateFormatter.localizedString(from: eventDateSelector.date, dateStyle: DateFormatter.Style.full, timeStyle: DateFormatter.Style.short) as String
print(eventsDates.description)
let eventSaved:[String: Any] = ["eventdate": eventsDates,"eventtitle":eventsTitleTextField.text!,"eventlocation":eventsLocation.text!]
eventsRef.child("Church Events").childByAutoId().setValue(eventSaved)
self.dismiss(animated: true, completion: nil)
}
}

All Items From Array Not In UITableView

Below is the CatalogViewController, which holds a tableview. The tableview has 1 prototype cell, ShopCell. When I print the items in the loop, they print correct, but when shown in the table, items are missing.
(Removing the shuffle() method does nothing & removing removeDuplicates(), items appear more than once). I didn't include the addToFavorites(cell: ShopCell) because I'm testing it. It does nothing.
protocol ShopCellDelegate {
func addToFavorites(cell: ShopCell)
}
class ShopCell: UITableViewCell {
#IBOutlet weak var productImageView: UIImageView!
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var priceLabel: UILabel!
#IBOutlet weak var descTV: UITextView!
#IBOutlet weak var favoriteButton: UIButton!
var delegate: ShopCellDelegate?
override func prepareForReuse() {
super.prepareForReuse()
self.productImageView.image = nil
self.titleLabel.text = ""
self.priceLabel.text = ""
self.descTV.text = ""
self.favoriteButton.isHidden = true
}
func setProduct(product: Product) {
productImageView.sd_setImage(with: URL(string: product.urlToImage!), placeholderImage: UIImage(named: "1024ELP.png"))
titleLabel.text = product.itemName!
priceLabel.text = product.priceTag!
descTV.text = product.itemDesc!
}
#IBAction func favOrUnfav(_ sender: UIButton) {
if let delegate = self.delegate {
delegate.addToFavorites(cell: self)
}
}
}
//
class CatelogViewController: UIViewController, GADInterstitialDelegate, SFSafariViewControllerDelegate, UITableViewDelegate, UITableViewDataSource, ShopCellDelegate {
#IBOutlet weak var tableView: UITableView!
static var shopType = String()
static var linkToVisit = String()
var myProducts = [Product]()
var productKeys = [String]()
var interstitial: GADInterstitial!
override func viewWillAppear(_ animated: Bool) {
visuals() // Sets Nav Bar color & changes cell size if device == ipad
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.navigationController?.navigationBar.tintColor = UIColor.black
if CatelogViewController.shopType == "Apparel" {
self.title = NSLocalizedString("Shop Apparel", comment: "")
fetchProductLinks(child1: "ProductList", child2: "Products")
}else{
self.title = NSLocalizedString("Shop Others", comment: "")
fetchProductLinks(child1: "OtherList", child2: "OtherProducts")
//shuffleItems()
}
if let index = self.tableView.indexPathForSelectedRow{
self.tableView.deselectRow(at: index, animated: true)
}
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myProducts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ShopCell
let product = myProducts[indexPath.row]
cell.delegate = self
cell.favoriteButton.isHidden = true
cell.setProduct(product: product)
return cell
}
func fetchProductLinks(child1: String, child2: String) {
let ref = Database.database().reference()
let prodRef = ref.child(child1).child(child2)
prodRef.observeSingleEvent(of: .value, with: { snapshot in
self.myProducts.removeAll()
for items in snapshot.children {
let item = items as! DataSnapshot
let product = item.value as! [String : String]
let name = product["Name"]
let link = product["Link"]
let img = product["urlToImage"]
let desc = product["Description"]
let price = product["Price"]
let newProduct = Product(urlToImage: img, itemName: name, itemLink: link, itemDesc: desc, priceTag: price)
self.myProducts.append(newProduct)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
self.myProducts = self.shuffleArray(array: self.myProducts) as! [Product]
self.myProducts = self.myProducts.removeDuplicates()
})
ref.removeAllObservers()
}
extension Array where Element:Equatable {
func removeDuplicates() -> [Element] {
var result = [Element]()
for value in self {
if result.contains(value) == false {
result.append(value)
}
}
return result
}
}
You shuffle your array and you remove duplicates, but you don't reload data after it. So reload data of table view
self.myProducts = self.shuffleArray(array: self.myProducts) as! [Product]
self.myProducts = self.myProducts.removeDuplicates()
self.tableView.reloadData()

How to sort an array from multiple textfields with one property

I was looking for an answer for this question but I couldn't find anything. I'm new in swift programming and also in stackoverflow, so I hope anyone can help me.
I try to make an app with an "EditViewController" which is there with multiple textfields for name, prename, etc.
I'm able to save this "phonebook" entries, but I'm not able to sort the array by the property name.
The editing interface is only this code:
import UIKit
class EditViewController: UIViewController {
#IBOutlet weak var vornameTextField: UITextField!
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var adresseTextField: UITextField!
#IBOutlet weak var hausnummerTextField: UITextField!
#IBOutlet weak var plzTextField: UITextField!
#IBOutlet weak var ortTextField: UITextField!
#IBOutlet weak var telefonnummerTextField: UITextField!
#IBOutlet weak var berufTextField: UITextField!
override func viewDidLoad()
{
super.viewDidLoad()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
}
The code for saving the textfields is:
import UIKit
class Telefonbuch: NSObject, NSCoding
{
var name: String!
var vorname: String!
var beruf: String!
var telefonnummer: String!
var adresse: String!
var hausnummer: String!
var plz: String!
var ort: String!
init(name: String, vorname: String, beruf:String, telefonnummer: String, adresse: String, hausnummer: String, plz: String, ort: String)
{
self.name = name
self.vorname = vorname
self.beruf = beruf
self.telefonnummer = telefonnummer
self.adresse = adresse
self.hausnummer = hausnummer
self.plz = plz
self.ort = ort
}
required init?(coder aDecoder: NSCoder) {
name = aDecoder.decodeObjectForKey("name") as? String
vorname = aDecoder.decodeObjectForKey("vorname") as? String
beruf = aDecoder.decodeObjectForKey("beruf") as? String
telefonnummer = aDecoder.decodeObjectForKey("telefonnummer") as? String
adresse = aDecoder.decodeObjectForKey("adresse") as? String
hausnummer = aDecoder.decodeObjectForKey("hausnummer") as? String
plz = aDecoder.decodeObjectForKey("plz") as? String
ort = aDecoder.decodeObjectForKey("ort") as? String
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: "name")
aCoder.encodeObject(vorname, forKey: "vorname")
aCoder.encodeObject(beruf, forKey: "beruf")
aCoder.encodeObject(telefonnummer, forKey: "telefonnummer")
aCoder.encodeObject(adresse, forKey: "adresse")
aCoder.encodeObject(hausnummer, forKey: "hausnummer")
aCoder.encodeObject(plz, forKey: "plz")
aCoder.encodeObject(ort, forKey: "ort")
}
static func saveArray(data: [Telefonbuch])
{
if data.count == 0 {return}
if let path = getFilePath() {
NSKeyedArchiver.archiveRootObject(data, toFile: path)
}
}
static func loadArray() -> [Telefonbuch]
{
if let path = getFilePath() {
if let result = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? [Telefonbuch]
{
return result
}
}
return [Telefonbuch]()
}
private static func getFilePath() -> String?
{
let pfd = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
if let pfad = pfd.first {
return pfad + "Kontakte.bin"
}else {
return nil
}
}
}
Now I would like to make the tableview, where I display the data, sorted and with header. But I'm not able to sort the [Telefonbuch] Array by property name.
import UIKit
class OverViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var addButton: UIBarButtonItem!
#IBOutlet weak var editButton: UINavigationItem!
var kontaktListe = Telefonbuch.loadArray()
override func viewDidLoad()
{
super.viewDidLoad()
tableView.dataSource = self
tableView.reloadData()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
#IBAction func addButtonPressed(sender: AnyObject)
{
performSegueWithIdentifier("editSegue", sender: self)
}
#IBAction func returnToMainController(segue: UIStoryboardSegue)
{
if let scr = segue.sourceViewController as? EditViewController
{
let newvorname = scr.vornameTextField.text
let newname = scr.nameTextField.text
let newadresse = scr.adresseTextField.text
let newhausnummer = scr.hausnummerTextField.text
let newpostleitzahl = scr.plzTextField.text
let newort = scr.ortTextField.text
let newtelefonnummer = scr.telefonnummerTextField.text
let newberuf = scr.berufTextField.text
let newKontakt = Telefonbuch(name: newname!, vorname: newvorname!, beruf: newberuf!, telefonnummer: newtelefonnummer!, adresse: newadresse!, hausnummer: newhausnummer!, plz: newpostleitzahl!, ort: newort!)
kontaktListe.insert(newKontakt, atIndex: 0)
Telefonbuch.saveArray(kontaktListe)
tableView.reloadData()
}
}
extension OverViewController: UITableViewDataSource
{
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 3
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return kontaktListe.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("ProtoCell", forIndexPath: indexPath)
let row = indexPath.row
cell.textLabel?.text = kontaktListe[row].name + " " + kontaktListe[row].vorname
cell.detailTextLabel?.text = kontaktListe[row].ort
return cell
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool
{
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
if editingStyle == .Delete
{
kontaktListe.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
tableView.reloadData()
}
}
extension OverViewController: UITableViewDelegate
{
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
performSegueWithIdentifier("detailSegue", sender: self)
}
}
Can anyone help me because I don't find a solution.
Thanks in advance.
You should be able to sort the array with:
kontaktListe.sort({ $0.name > $1.name })

How can I return multiple elements in a cell?

I would like to return multiple elements of a cell. How can I do it? This is the code I'm working on
//
// TableViewControllerCompiti.swift
// Secondo B
//
// Created by Edoardo on 23/12/15.
// Copyright © 2015 ERC. All rights reserved.
//
import UIKit
import Parse
class TableViewControllerCompiti: UITableViewController {
var selfTable: NSMutableArray = NSMutableArray()
#IBOutlet var MessageTable: UITableView!
#IBOutlet weak var Compiti: UILabel!
#IBOutlet weak var DescrizioneCompiti: UITextView!
#IBOutlet weak var DataCompiti: UILabel!
var messagesArray: [String] = [String]()
var descriptionArray: [String] = [String]()
var dateArray: [String] = [String]()
override func viewDidLoad() {
super.viewDidLoad()
func retrieveMessages() {
let query = PFQuery(className: "Compiti")
query.findObjectsInBackgroundWithBlock {
(remoteObjects: [PFObject]?, error: NSError?) -> Void in
for messageObject in remoteObjects! {
let messageText: String? = (messageObject as PFObject) ["Materia"] as? String
let descriptionText: String? = (messageObject as PFObject) ["Compiti"] as? String
let date: String? = (messageObject as PFObject) ["Data"] as? String
if messageText != nil {
self.messagesArray.append(messageText!)
}
if descriptionText != nil {
self.descriptionArray.append(descriptionText!)
}
if date != nil {
self.dateArray.append(date!)
}
}
self.MessageTable.reloadData()
}
}
retrieveMessages()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell?()
cell = tableView.dequeueReusableCellWithIdentifier("cell")
Compiti.text = self.messagesArray[indexPath.row]
DataCompiti.text = self.dateArray[indexPath.row]
DescrizioneCompiti.text = self.descriptionArray[indexPath.row]
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "ReUseCell")
}
return cell!
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.messagesArray.count
}
}
When I run it, the simulator just returns a bunch of empty cells. How can I do to return the elements?
Remark From your code:
you cannot implement and call the function inside of viewDidLoad(), you implement all functions/methods outside of the life cycle then call inside.
I don't think its a good idea of having three different arrays to contain your data,you should learn struct or class data structures to group your data since you are getting them from the same class.
struct myDataContainer
{
var message:String?
var descriptionText:String?
var date:String?
}
var arrayOfContainers = [myDataContainer]() //<-- this will be your new array
I saw that you had a customize cell where you wanted to have 2 Labels and UITextView.. you should create a subclass of UITableViewCell then group them inside.
class CustomizeCell :UITableViewCell
{
#IBOutlet weak var Compiti: UILabel!
#IBOutlet weak var DescrizioneCompiti: UITextView!
#IBOutlet weak var DataCompiti: UILabel!
} //<--- Subclass of UITableViewCell above
struct myDataContainer
{
var message:String?
var descriptionText:String?
var date:String?
}
class TableViewControllerCompiti: UITableViewController {
var arrayOfContainers = [myDataContainer]() //<-- this will be your new array
override func viewDidLoad()
{
super.viewDidLoad()
retrieveMessages() //<--- call function
}
func retrieveMessages()
{
var objectT = myDataContainer()
let query = PFQuery(className: "Compiti")
query.findObjectsInBackgroundWithBlock {(objects: [PFObject]?, error: NSError?) -> Void in
if let remoteObjects = objects
{
for messageObject in remoteObjects
{
let messageText = messageObject["Materia"] as? String
let description = messageObject["Compiti"] as? String
let date = messageObject["Data"] as? String
objectT.message = messageText!
objectT.descriptionText = description!
objectT.date = date!
self.arrayOfContainers.append(objectT)
}
self.tableView.reloadData()
}
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomizeCell
// as! CustomizeCell technically speaking make sure that we access our customize cell
let data = self.arrayOfContainers[indexPath.row]
cell.Compiti.text = data.message
cell.DataCompiti.text = data.descriptionText
cell.DescrizioneCompiti.text = data.date
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.arrayOfContainers.count
}
}