i'm running a query to Firebase and the results are displaying in a custom cell. The cell has a UIButton that when tapped it goes to another view controller where the user can enter info. The question i have is, how do i send the array in the custom cell to the next view controller? i need to send the array so i can reference the subcollection of info i'm going to add for each array. Segue is working properly, when i print to the console, the array is empty "nil". Any help is greatly appreciated.
Custom Cell
import UIKit
import Firebase
protocol PatCellCommentsDelegate {
func patCommentBtnTapped (ptcomments: [Comment])
}
class PatdataCell: UITableViewCell {
#IBOutlet weak var ptnameLbl: UILabel!
#IBOutlet weak var dobLbl: UILabel!
#IBOutlet weak var finLbl: UILabel!
#IBOutlet weak var officemdLbl: UILabel!
#IBOutlet weak var assignedmdLbl: UILabel?
#IBOutlet weak var appnameLbl: UILabel!
#IBOutlet weak var assigneddateLbl: UILabel!
#IBOutlet weak var roomnumberLbl: UILabel?
#IBOutlet weak var diagnosesLbl: UILabel!
#IBOutlet weak var reasonforadmitorconsultLbl: UILabel!
#IBOutlet weak var goalofhospitalizationLbl: UILabel!
#IBOutlet weak var seenoseeLbl: UILabel?
#IBOutlet weak var notestocboLbl: UILabel!
#IBOutlet weak var numCommentsLbl: UILabel!
#IBOutlet weak var hospitalLbl: UILabel!
#IBOutlet weak var teamLbl: UILabel!
#IBOutlet weak var addCommentBtn: UIButton!
var ptdata: PTData!
var ptcomments = [Comment]()
var delegate: PatCellCommentsDelegate?
override func awakeFromNib() {
super.awakeFromNib()
}
func configurePatDataCell(ptdata: PTData, delegate:
PatCellCommentsDelegate) {
self.ptdata = ptdata
self.delegate = delegate
ptnameLbl.text = ptdata.ptname
dobLbl.text = ptdata.dob
finLbl.text = ptdata.fin
officemdLbl.text = ptdata.officemd
assignedmdLbl?.text = ptdata.assignedmd
appnameLbl.text = ptdata.app
assigneddateLbl.text = ptdata.assigneddate
roomnumberLbl?.text = ptdata.room
diagnosesLbl.text = ptdata.diagnoses
reasonforadmitorconsultLbl.text = ptdata.reasonforadmitorconsult
goalofhospitalizationLbl.text = ptdata.goalofhospitalization
seenoseeLbl?.text = ptdata.seenosee
notestocboLbl.text = ptdata.notestocbo
numCommentsLbl.text = ptdata.comments
hospitalLbl.text = ptdata.hosp
teamLbl.text = ptdata.team
}
#IBAction func addCommentBtnTapped(_ sender: Any) {
//trying to send data to commentsVC from this cell
delegate?.patCommentBtnTapped(ptcomments: self.ptcomments)
}
}
View Controller
import UIKit
import Firebase
import SVProgressHUD
class PatdataVC: UIViewController, UITableViewDelegate,
UITableViewDataSource, PatCellCommentsDelegate {
#IBOutlet weak var patDataTableView: UITableView!
var ptdatas = [PTData]()
var ptComments = [Comment]()
override func viewDidLoad() {
super.viewDidLoad()
patDataTableView.delegate = self
patDataTableView.dataSource = self
patDataTableView.rowHeight = 1150
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToComments" {
let commtsVC = segue.destination as! CommentsVC
commtsVC.ptComments = ptComments
SVProgressHUD.dismiss()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
return ptdatas.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
if tableView == patDataTableView {
let cell = tableView.dequeueReusableCell(withIdentifier:
"PatdataCell", for: indexPath) as? PatdataCell
cell!.configurePatDataCell(ptdata: ptdatas[indexPath.row],
delegate: self)
return cell!
}
return UITableViewCell()
}
func patCommentBtnTapped (ptcomments: [Comment]) {
self.ptComments = ptcomments
performSegue(withIdentifier: "goToComments", sender: self)
}
}
CommentsVC
import UIKit
import Firebase
import FirebaseFirestore
class CommentsVC: UIViewController, UITableViewDelegate,
UITableViewDataSource, CommentsDelegate {
#IBOutlet weak var commentTableView: UITableView!
#IBOutlet weak var addCommentTxt: UITextField!
#IBOutlet weak var keyboardView: UIView!
var ptComments = [Comment]()
var commentsPtData: Comment!
var commentRef: DocumentReference!
var username: String!
var commentListener : ListenerRegistration!
let firestore = Firestore.firestore()
override func viewDidLoad() {
super.viewDidLoad()
commentTableView.dataSource = self
commentTableView.delegate = self
commentTableView.rowHeight = 110
//commentRef =
firestore.collection(PTLIST_REF).document(commentsPtData.documentId)
// if let name = Auth.auth().currentUser?.displayName{
// username = name
// }
self.view.bindToKeyboard()
}
override func viewDidAppear(_ animated: Bool) {
commentListener =
firestore.collection(PTLIST_REF).document(self.commentsPtData
.documentId)
.collection(COMMENTS_REF)
.order(by: TIMESTAMP, descending: false)
.addSnapshotListener({ (snapshot, error) in
guard let snapshot = snapshot else {
debugPrint("Error Fetching comments: \(Error.self)")
return
}
self.ptComments.removeAll()
self.ptComments = Comment.parseData(snapshot: snapshot)
self.commentTableView.reloadData()
})
}
override func viewDidDisappear(_ animated: Bool) {
commentListener.remove()
}
func commentOptionsTapped(commentsCellPtData: Comment) {
let alert = UIAlertController(title: "Edit Comment", message: "You
can delete or edit", preferredStyle: .actionSheet)
let deleteAction = UIAlertAction(title: "Delete Comment", style:
.default) { (action) in
self.firestore.runTransaction({ (transaction, errorPointer) ->
Any? in
let ptListDocument: DocumentSnapshot
do {
try ptListDocument =
transaction.getDocument(Firestore.firestore()
.collection(PTLIST_REF).document(self.commentsPtData.documentId))
} catch let error as NSError {
debugPrint("Fetch Error: \ .
(error.localizedDescription)")
return nil
}
guard let oldNumComments = ptListDocument.data()!
[NUM_COMMENTS] as? Int else { return nil }
transaction.updateData([NUM_COMMENTS : oldNumComments -
1], forDocument: self.commentRef!)
let commentRef =
self.firestore.collection(PTLIST_REF).document(self
.commentsPtData.documentId).collection(COMMENTS_REF)
.document(commentsCellPtData.documentId!)
transaction.deleteDocument(commentRef)
return nil
}) { (object, error) in
if let error = error {
debugPrint("transaction failed: \(error)")
} else {
alert.dismiss(animated: true, completion: nil)
}
}
}
let editAction = UIAlertAction(title: "Edit Comment", style:
.default) { (action) in
self.performSegue(withIdentifier: "toEditComment", sender:
(commentsCellPtData, self.commentsPtData))
alert.dismiss(animated: true, completion: nil)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel,
handler: nil)
alert.addAction(deleteAction)
alert.addAction(editAction)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
#IBAction func addCommentTapped(_ sender: Any) {
guard let commentTxt = addCommentTxt.text else { return }
firestore.runTransaction({ (transaction, errorPointer) -> Any? in
let ptListDocument: DocumentSnapshot
do {
try ptListDocument =
transaction.getDocument(Firestore.firestore()
.collection(PTLIST_REF).document(self.commentsPtData.documentId))
} catch let error as NSError {
debugPrint("Fetch Error: \(error.localizedDescription)")
return nil
}
guard let oldNumComments = ptListDocument.data()!
[NUM_COMMENTS] as? Int else { return nil }
transaction.updateData([NUM_COMMENTS : oldNumComments + 1],
forDocument: self.commentRef!)
let newCommentRef =
self.firestore.collection(PTLIST_REF).document((self
.commentsPtData.documentId)).collection(COMMENTS_REF).document()
transaction.setData([
COMMENT_TXT : commentTxt,
TIMESTAMP : FieldValue.serverTimestamp(),
USERNAME : self.username!,
USER_ID : Auth.auth().currentUser?.uid ?? ""
], forDocument: newCommentRef)
return nil
}) { (object, error) in
if let error = error {
debugPrint("transaction failed: \(error)")
} else {
self.addCommentTxt.text = ""
self.addCommentTxt.resignFirstResponder()
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
return ptComments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier:
"CommentCell", for: indexPath) as? CommentCell {
cell.configureCell(comment: ptComments[indexPath.row],
delegate: self)
return cell
}
return UITableViewCell()
}
}
In your source code ptcomments property in Custom Cell not set anywhere, it is empty in cell.
Please set correct value for ptcomments
UPDATE:
You try add line like self.comments = ptdata.commentsList to function configurePatDataCell
Related
Hi im trying to build ordering food application but i faced a problem which is i want to separate the cartTableViewController for multi viewController.
i don’t know how to explain it because my english is soo bad but i will try my best to explain it … what i mean is let say that the user has been added items from burgerKingViewController to the cartTableViewController and he move on to mcdonaldsViewController to add items to the cartTableViewController ,, here i want to show an alert for the user saying that he has an items in his cart from burgerKingViewController and he should delete it so he can add items from mcdonaldsViewController
to simplify it more .. i want the cartTableViewController handle only one restaurant so i can take the order from firebase.
thanks.
this is the code i use it to add the item to the cartTableViewController
import UIKit
struct userData {
static var selectedItem: Item? = nil
static var selectedItems: [Item] = []
static func selectedItemsPrice() -> Double {
var result: Double = 0
for item in selectedItems {
result = result + item.price
}
return result
}
static func allItemsToString() -> String {
var allNames: [String] = []
for item in selectedItems {
allNames.append(item.name)
}
return allNames.joined(separator: ", ")
}
}
struct Item: Equatable {
static let items : [Item] = {
let food: Item = .init(image: UIImage(named: “food”)!, name: “food, price: 50)
return [food]
}()
var image: UIImage?
var name: String
var price: Double
}
this is the cartTableViewController
import UIKit
class cartTableViewController: UITableViewController {
#IBOutlet var checkOutPressed: UIButton!
#IBOutlet var priceLabel: UILabel!
#IBOutlet var cartView: UIView!
#IBOutlet var totalOrder: UILabel!
#IBOutlet var cartTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
overrideUserInterfaceStyle = .light
checkOutPressed.layer.cornerRadius = 4.0
}
override func viewWillAppear(_ animated: Bool) {
priceLabel.text = "\(userData.selectedItemsPrice())"
totalOrder.text = "\(userData.allItemsToString())"
super.viewWillAppear(animated)
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return userData.selectedItems.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
105
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cartCell") as! cartTableViewCell
cell.cartImage.layer.masksToBounds = true
cell.cartImage.layer.cornerRadius = 8
cell.cartImage.translatesAutoresizingMaskIntoConstraints = false
cell.cartImage.contentMode = .scaleAspectFill
cell.cartLabel.textColor = .black
cell.cartLabel.translatesAutoresizingMaskIntoConstraints = false
cell.selectionStyle = .none
let cart = userData.selectedItems[indexPath.row]
cell.cartImage.image = cart.image
cell.cartLabel.text = cart.name
cell.priceLabel1.text = “\(cart.price)"
return cell
}
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
// Override to support editing the table view.
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// remove the item from the data model
userData.selectedItems.remove(at: indexPath.row)
// delete the table view row
tableView.deleteRows(at: [indexPath], with: .fade)
priceLabel.text = "\(userData.selectedItemsPrice())"
totalOrder.text = "\(userData.allItemsToString())"
} else if editingStyle == .insert {
// Not used in our example, but if you were adding a new row, this is where you would do it.
}
}
#IBAction func checkOutPressed(_ sender: UIButton) {
if priceLabel.text! == "" || totalOrder.text! == "" {
// Alert
let optionMenu = UIAlertController(title: nil, message: “please add item”, preferredStyle: .alert)
// Add actions to the menu
let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler:
nil)
optionMenu.addAction(cancelAction)
// Display the menu
self.present(optionMenu, animated: true, completion: nil)
}
}
}
this is burgerKingViewController
import UIKit
class burgerKingViewController: UIViewController {
#IBOutlet var burgerKingImage: UIImageView!
#IBOutlet var burgerKingName: UILabel!
#IBOutlet var burgerKingPrice: UILabel!
#IBOutlet var makeOrder: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
overrideUserInterfaceStyle = .light
makeOrder.layer.cornerRadius = 4.0
}
#IBAction func makeOrder(_ sender: UIButton) {
let alert = UIAlertController(title: "", message: “done”, preferredStyle: .alert)
self.present(alert, animated: true, completion: nil)
let when = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: when) {
// your code with delay
alert.dismiss(animated: true, completion: nil)
}
userData.selectedItems.append(Item(image: UIImage(named: “burgerKing”), name: “burgerKing”, price: Double(10.000)))
self.aimateView(sender)
}
fileprivate func aimateView( _ viewToAnimate:UIView) {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 2, options: .curveEaseIn, animations: {
viewToAnimate.transform = CGAffineTransform(scaleX: 0.92, y: 0.92)
}) { (_) in
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 2, options: .curveEaseIn, animations: {
viewToAnimate.transform = CGAffineTransform(scaleX: 1, y: 1)
}, completion: nil)
}
}
}
and this is mcdonaldsViewController
import UIKit
class mcdonaldsViewController: UIViewController {
#IBOutlet var mcdonaldsImage: UIImageView!
#IBOutlet var mcdonaldsName: UILabel!
#IBOutlet var mcdonaldsPrice: UILabel!
#IBOutlet var makeOrder: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
overrideUserInterfaceStyle = .light
makeOrder.layer.cornerRadius = 4.0
}
#IBAction func makeOrder(_ sender: UIButton) {
let alert = UIAlertController(title: "", message: “done”, preferredStyle: .alert)
self.present(alert, animated: true, completion: nil)
// change to desired number of seconds (in this case 5 seconds)
let when = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: when) {
// your code with delay
alert.dismiss(animated: true, completion: nil)
}
userData.selectedItems.append(Item(image: UIImage(named: "mcdonalds"), name: "mcdonalds", price: Double(10.000)))
self.aimateView(sender)
}
fileprivate func aimateView( _ viewToAnimate:UIView) {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 2, options: .curveEaseIn, animations: {
viewToAnimate.transform = CGAffineTransform(scaleX: 0.92, y: 0.92)
}) { (_) in
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 2, options: .curveEaseIn, animations: {
viewToAnimate.transform = CGAffineTransform(scaleX: 1, y: 1)
}, completion: nil)
}
}
}
Hi im trying to pass data from one viewController to tableViewCell without using the segue, i tried with delegate and nsNotificationCenter but it did not work with me so, help me please.
this is my code for the view controller which i want to pass data from it ( imageViewSweet, LabelSweet )
import UIKit
class sweetAndSalty4ViewController: UIViewController {
#IBOutlet var imageViewSweet: UIImageView!
#IBOutlet var labelsweet: UILabel!
#IBOutlet var sweeetTable: UITableView!
var passText: String?
override func viewDidLoad() {
passText = labelsweet.text
super.viewDidLoad()
}
#IBAction func sendData(_ sender: UIButton) {
let sb = storyboard?.instantiateViewController(withIdentifier: "cartVC") as! cartViewController
sb.priceLabel = labelsweet
present(sb, animated: true, completion: nil)
}
}
and this is the code for the viewController which i want to display the image and the label from the swwetAndSalty4ViewController .
import UIKit
class cartViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var priceLabel: UILabel!
var passText: String?
var cartItem = ""
#IBOutlet var cartTable: UITableView!
override func viewDidLoad() {
cartTable.delegate = self
cartTable.dataSource = self
// foodTable.separatorStyle = .none
view.backgroundColor = UIColor.init(red: 228/255, green: 230/255, blue: 234/255, alpha: 1)
navigationItem.title = "My Cart"
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cartItem.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
240
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cartCell") as! cartTableViewCell
cell.layer.cornerRadius = 30
cell.layer.borderWidth = 15.0
cell.layer.borderColor = UIColor.white.cgColor
cell.cartImage.layer.masksToBounds = true
cell.cartImage.layer.cornerRadius = 2
cell.cartImage.translatesAutoresizingMaskIntoConstraints = false
cell.cartImage.contentMode = .scaleAspectFill
cell.cartLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
cell.cartLabel.textColor = .black
cell.cartLabel.translatesAutoresizingMaskIntoConstraints = false
cell.cartLabel.backgroundColor = .systemGray5
cell.cartLabel.text = ""
cell.cartImage.image = UIImage(named: "")
// cell.contentView.backgroundColor = .white
return cell
}
}
There you go, i've also organized your code:
First View Controller:
import UIKit
struct myVariables {
static var kinder: String! = nil
static var kinderImage: UIImage! = nil
}
class sweetAndSalty4ViewController: UIViewController {
#IBOutlet var imageViewSweet: UIImageView!
#IBOutlet var labelsweet: UILabel!
#IBOutlet var sweeetTable: UITableView!
var passText: String?
override func viewDidLoad() {
super.viewDidLoad()
passText = labelsweet.text
}
#IBAction func sendData(_ sender: UIButton) {
let sb = storyboard?.instantiateViewController(withIdentifier: "cartVC") as! cartViewController
sb.priceLabel = labelsweet
present(sb, animated: true, completion: nil)
}
func sendDataToMyVariables(kinder: String, kinderImage: UIImage) {
myVariables.kinder = kinder
myVariables.kinderImage = kinderImage
}
}
and then, after you send the variables you can use them anywhere in your code by doing
myVariables.kinder // get the string
myVariables.kinderImage // get the image
I'm trying to create a photo album via UIImagePicker into a CollectionView and cannot get it to segue to said photo again in a detailed UIViewController. Pulling my hair out and this is just a tutorial as I have just started coding!
Can anyone tell me what I'm doing wrong?
var testItems = [Person]()
#IBAction func addItem() {
addNewPerson()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "DetailSegue" {
if let dest = segue.destination as? DetailsViewController,
let index = sender as? IndexPath {
dest.detailedImageHi = testItems[index.row]
}
}
}
THE NS OBJECT FILE IS AS FOLLOWS:
class Person: NSObject {
var imageHi: String
init(imageHi: String){
self.imageHi = imageHi
}
}
DetailsViewController:
class DetailsViewController: UIViewController {
var selection: String!
var detailedImageHi: UIImage!
#IBOutlet private weak var detailsLabel: UILabel!
#IBOutlet private weak var detailedImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
detailsLabel.text = selection
detailedImage.image = detailedImageHi
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
import UIKit
class CollectionViewCell: UICollectionViewCell {
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var selectionImage: UIImageView!
}
I have been trying to fix this for 4 days and still no luck so any help would be appreciated. I am trying to create a table view where workers can upload their profiles and users can scroll through to see which ones they like (see simulator photo). However, when I use indexPath.row it fills out the whole cell when I only want it to fill out one label so I can configure the different labels with the data I want.
Here is my Table view controller code:
import UIKit
import FirebaseDatabase
import FirebaseStorage
struct Worker {
var name: String!
var price: String!
}
class SelectATaskerTableViewController: UITableViewController {
var ref: DatabaseReference!
var myList:[String] = []
#IBOutlet var myTableView: UITableView!
var handle: DatabaseHandle!
var storageHandle: StorageHandle!
var storageRef: StorageReference!
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = 111
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func viewWillAppear(_ animated: Bool) {
myTableView.delegate = self
myTableView.dataSource = self
ref = Database.database().reference()
storageRef = Storage.storage().reference()
handle = ref.child("WorkerProfile").child("Name").observe(.childAdded, with: { (snapshot) in
if let item = snapshot.value as? String {
self.myList.append(item)
self.myTableView.reloadData()
}
})
}
#IBAction func reset(_ sender: Any) {
Database.database().reference().child("WorkerProfile").removeValue()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return myList.count
}
var nameText: String!
var pricePerHourText: String!
var extraDetailsText: String!
var profilePicImage: UIImage!
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:MyCellTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! MyCellTableViewCell
cell.firstName.text = myList[indexPath.row]
cell.pricePerHour.text = myList[indexPath.row]
// cell.extraDetails.text = extraDetailsText
// cell.profilePic.image = profilePicImage
// Configure the cell...
return cell
}
And my custom table view cell code
import UIKit
class MyCellTableViewCell: UITableViewCell {
#IBOutlet weak var firstName: UILabel!
#IBOutlet weak var pricePerHour: UILabel!
#IBOutlet weak var extraDetails: UILabel!
#IBOutlet var profilePic: UIImageView!
}
I have a problem with an array of data, in this data array I send the name of 6 images so that later they are loaded in a CollectionView, the 6 images load well, without any problem, but when I add a String value to send it gives me a error that is empty:
This is my class where is my data array:
import UIKit
class HBook{
var imagenB: UIImage!
var estatus: String!
init(estatus: String, imagenB: UIImage) {
self.estatus = estatus
self.imagenB = imagenB
}
class func getData() -> [HBook]{
let rawData = [
["imagenB":"book1"],
["imagenB":"book2"],
["imagenB":"book3"],
["imagenB":"book4"],
["imagenB":"book5"],
["imagenB":"book6"],
["estatus":"No reservado"]
]
var hbook:[HBook] = []
for item in rawData{
hbook.append(HBook(estatus: item["estatus"]!, imagenB: UIImage(named: item["imagenB"]!)!))
}
return hbook
}
}
I print my data array to see which variable is empty, but apparently all have an assigned value:
I do not know why I'm sending an empty value.
This information was retrieved in another class that has a CollectionView and a Label, the method where I passed the information is in the cellForItemAt method:
class DetailViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
#IBOutlet weak var contenedorCollection: UIView!
#IBOutlet weak var myCollection: UICollectionView!
#IBOutlet weak var pages: UIPageControl!
#IBOutlet weak var estatus: UILabel!
var hbook = HBook.getData()
var nombreH = ""
override func viewDidLoad() {
super.viewDidLoad()
pages.numberOfPages = hbook.count
self.title = nombreH
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return hbook.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CellCollectionViewCell
cell.imageview.image = hbook[indexPath.row].imagenB
estatus.text = hbook[indexPath.row].estatus
return cell
}
I think the problem is in data class. Please replace your HBook class with following code and it will work without any further change :
class HBook{
var imagenB: UIImage?
var estatus: String?
init(estatus: String? = nil, imagenB: UIImage? = nil) {
self.estatus = estatus
self.imagenB = imagenB
}
class func getData() -> [HBook]{
let rawData = [
["imagenB":"book1","estatus":"No reservado"],
["imagenB":"book2","estatus":"No reservado"],
["imagenB":"book3","estatus":"No reservado"],
["imagenB":"book4","estatus":"No reservado"],
["imagenB":"book5","estatus":"No reservado"],
["imagenB":"book6","estatus":"No reservado"]
]
var hbook:[HBook] = []
for item in rawData{
if let image = item["itemnB"]{
hbook.append(HBook(estatus: item["estatus"], imagenB:UIImage(named:image)))
}else{
hbook.append(HBook(estatus: item["estatus"]))
}
}
return hbook
}
}