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

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
}
}

Related

How to add data into Firestore Swift by tapping on a cell

I have more restaurants , each have diferent food.Look here
This is how im retrieving data from the Firestore. In the previous controller I have a list of restaurants, each contains a list food.
struct Food {
var photoKeyRestaurant: String
var foodName: String
var foodDescription: String
var restaurantName: String
var priceFood: Int
}
class RestaurantViewController: UIViewController {
var restaurantName: String!
var food: [Food] = []
private let tableView: UITableView = {
let table = UITableView()
return table
}()
func getDatabaseRecords() {
let db = Firestore.firestore()
// Empty the array
food = []
db.collection("RestaurantViewController").whereField("restaurantName", isEqualTo: restaurantName).getDocuments { (snapshot, error) in
if let error = error {
print(error)
return
} else {
for document in snapshot!.documents {
let data = document.data()
let newEntry = Food(photoKeyRestaurant: data["photoKeyRestaurant"] as! String, foodName: data["foodName"] as! String, foodDescription: data["foodDescription"] as! String, restaurantName: data["restaurantName"] as! String , priceFood: data["priceLabel"] as! Int
)
self.food.append(newEntry)
}
}
DispatchQueue.main.async {
// self.datas = self.filteredData
self.tableView.reloadData()
}
}
}
How can I add the data of the selected cell by pressing on + to Firestore in this function ?
I'vrea create a protocol in my FoodTableViewCell , and I've called it in the RestaurantViewController.
func diddTapButtonCell(_ cell: FoodTableViewCell) {
let db = Firestore.firestore()
db.collection("cart").addDocument.(data: foodName) { (err) in
}
Edited: Added Table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return food.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FoodTableViewCell", for: indexPath) as! FoodTableViewCell
cell.delegate = self
let mancare = food[indexPath.row]
let storageRef = Storage.storage().reference()
let photoRef = storageRef.child(mancare.photoKeyRestaurant)
cell.foodImage.sd_setImage(with: photoRef)
cell.descriptionLabel.text = mancare.foodDescription
cell.foodNameLabel.text = mancare.foodName
cell.priceLabel.text = "\(mancare.priceFood) lei"
//Fac ca imaginea sa fie cerc - start
cell.foodImage.layer.borderWidth = 1
cell.foodImage.layer.masksToBounds = false
cell.foodImage.layer.borderColor = UIColor.black.cgColor
cell.foodImage.layer.cornerRadius = cell.foodImage.frame.height/2
cell.foodImage.clipsToBounds = true
//Fac ca imaginea sa fie cerc - finish
return cell
}
This is my tableview cell code
protocol CustomCellDelegate {
func diddTapButtonCell (_ cell: FoodTableViewCell)
}
class FoodTableViewCell: UITableViewCell {
var delegate: CustomCellDelegate?
#IBOutlet weak var foodImage: UIImageView!
#IBOutlet weak var foodNameLabel: UILabel!
#IBOutlet weak var descriptionLabel: UILabel!
#IBOutlet weak var priceLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
#IBAction func addToCart(_ sender: Any) {
delegate?.diddTapButtonCell(self)
}
}
https://firebase.google.com/docs/firestore/manage-data/add-data
And here is an example from one of my projects for adding data to firestore.
func updateDocument(rootCollection : String, doc: String, newValueDict: [String : Any], completion:#escaping (Bool) -> Void = {_ in }) {
let db = Firestore.firestore()
db.collection(rootCollection).document(doc).setData(newValueDict, merge: true){ err in
if let err = err {
print("Error writing document: \(err)")
completion(false)
}else{
completion(true)
}
}
}

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

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.

Updating Realm through a custom button on the UITableViewCell

I have a tableview of "Books" that are stored in Realm. I want to set the "CurrentBook" property to "True" when hitting a button on a custom UITableViewCell.
I believe my error has something to do with getting the correct book value in "func selectCurrentBook", when I use an optional like below nothing happens.
#objc func selectCurrentBook(sender: UIButton) {
try! realm.write {
book?.currentlyReading = true
}
}
When I don't use an optional for book and use book.currentlyReading = true I get the error "Unexpectedly found nil while implicitly unwrapping an Optional value:"
Am I incorrectly passing the book value somewhere? I can't seem to find out how. Maybe I'm delegating wrong?
My TableViewCell is:
import UIKit
import RealmSwift
protocol MyBooksDelegate {
func currentlyReadingButton()
}
class MyBooksTableViewCell: UITableViewCell {
let realm = try! Realm()
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var authorLabel: UILabel!
#IBOutlet weak var smallThumbnailImageView: UIImageView!
#IBOutlet weak var currentlyReadingButton: UIButton!
#IBAction func currentlyReadingButton(_ sender: Any) {
}
private var book: Book!
func loadImage(smallThumbnailURL: String) {
let imageURL = URL(string: smallThumbnailURL ?? "")
smallThumbnailImageView.sd_setImage(with: imageURL)
}
func configureCell(book: Book, delegate: MyBooksDelegate?) {
titleLabel.text = book.bookTitle
authorLabel.text = book.bookAuthor
loadImage(smallThumbnailURL: book.bookSmallThumbnailImageURL)
currentlyReadingButton.addTarget(self, action: #selector(selectCurrentBook(sender:)), for: .touchUpInside)
}
#objc func selectCurrentBook(sender: UIButton) {
try! realm.write {
book?.currentlyReading = true
}
}
}
My View Controller with TableView is :
import SwiftyJSON
import RealmSwift
class BooksViewController: UIViewController, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var myBooksTableView: UITableView!
let realm = try! Realm()
var books: Results<Book>?
// Search Bar Properties
var searchParameter = "intitle"
var booksArray: [Book] = []
override func viewDidLoad() {
super.viewDidLoad()
loadBooks()
// Setting up the TableView
self.myBooksTableView.delegate = self
self.myBooksTableView.dataSource = self
self.myBooksTableView.rowHeight = 120.0
// Setup Title
title = "My Books"
// navigationController?.navigationBar.prefersLargeTitles = true
}
override func viewWillAppear(_ animated: Bool) {
navigationController?.navigationBar.barStyle = .black
loadBooks()
}
func loadBooks() {
books = realm.objects(Book.self).sorted(byKeyPath: "DateCreated", ascending: false)
myBooksTableView.reloadData()
}
// TABLEVIEW
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return books?.count ?? 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "MyBooksTableViewCell", for: indexPath) as? MyBooksTableViewCell {
cell.configureCell(book: (books?[indexPath.row])!, delegate: self as? MyBooksDelegate)
// cell.selectionStyle = UITableViewCell.SelectionStyle.none
return cell
} else {
return UITableViewCell()
}
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "myBooksTOMyBooksDetail", sender: self)
myBooksTableView.deselectRow(at: indexPath, animated: true)
}
And my Book Model is:
class Book: Object {
#objc dynamic var bookTitle: String!
#objc dynamic var bookAuthor: String!
#objc dynamic var bookSmallThumbnailImageURL: String!
#objc dynamic var bookThumbnailImageURL: String!
#objc dynamic var bookDescription: String!
#objc dynamic var bookISBN_13: String!
#objc dynamic var currentlyReading = false
#objc dynamic var DateCreated = Date()
#objc dynamic var WordID = UUID().uuidString
// words
let words = List<Word>()
override static func primaryKey() -> String? {
return "WordID"
}
}
The most compatible syntax is
currentlyReadingButton.addTarget(self, action: #selector(selectCurrentBook), for: .touchUpInside)
and
#objc func selectCurrentBook(_ sender: UIButton) {
However as the cell is custom anyway I'd prefer an IBAction over target/action
And the protocol MyBooksDelegate seems to be unused.
Side note:
Force unwrap the cell
let cell = tableView.dequeueReusableCell(withIdentifier: "MyBooksTableViewCell", for: indexPath) as! MyBooksTableViewCell
A crash – with report – reveals a design mistake which can be fixed instantly. With the if let you'll see nothing and have no clue why.
Update:
The crash occurs because you don't set book in the cell, add the first line after the {
func configureCell(book: Book, delegate: MyBooksDelegate?) {
self.book = book
titleLabel.text = book.bookTitle
...

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 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
}
}