Handle items from multi viewController - arrays

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

Related

How do you save new index location in persistentcontainer?

I have a tableview where I have added the ability to move the location of rows. I am able to use the "swapAt" function to update my array and it works fine. The problem is that when I close and re-open the app, the rows continue to show in their old IndexPath. How can I also update the index location in the PersistentContainer so that when I open the app, it is updated with the new IndexPath?
I tried calling the save method of the context but it does not work.
import UIKit
import CoreData
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var tableView: UITableView!
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var toDoList = [Item] ()
var count: Int {
toDoList.count
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addItem))
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(editItem))
title = "Todo"
loadItem()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return toDoList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath)
cell.textLabel?.text = toDoList [indexPath.row].title
if toDoList[indexPath.row].checkmark == true {
cell.accessoryType = .checkmark }
else {
cell.accessoryType = .none
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if toDoList[indexPath.row].checkmark == false {
toDoList[indexPath.row].checkmark = true } else {
toDoList[indexPath.row].checkmark = false
}
tableView.reloadData()
saveItem()
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
toDoList.swapAt(sourceIndexPath.row, destinationIndexPath.row)
saveItem()
}
#objc func addItem () {
let ac = UIAlertController(title: "Add new category", message: nil, preferredStyle: .alert)
var textField = UITextField()
let submitAction = UIAlertAction(title: "Add", style: .default) { (action) in
let newItem = Item(context: self.context)
newItem.title = textField.text
newItem.checkmark = false
newItem.order = Int64(self.count)
self.toDoList.append(newItem)
self.saveItem()
}
ac.addTextField { (alertTextField) in
alertTextField.placeholder = "Create new item"
textField = alertTextField
}
ac.addAction(submitAction)
present(ac, animated: true, completion: nil)
}
func saveItem () {
do {
try context.save()
} catch {
print("This is the \(error)")
}
self.tableView.reloadData()
}
func loadItem () {
let request: NSFetchRequest<Item> = Item.fetchRequest()
let sortRequest = NSSortDescriptor(key: "order", ascending: true)
request.sortDescriptors = [sortRequest]
do {
toDoList = try context.fetch(request)
} catch {
print("the error is \(error)")
}
tableView.reloadData()
}
#objc func editItem () {
if tableView.isEditing {
tableView.isEditing = false
} else {
tableView.isEditing = true
}}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
context.delete(toDoList[indexPath.row])
saveItem()
self.toDoList.remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
}
I would tackle this problem by having an index property in the Coredata entity; this index reflects the position of the element in the table view. In the swapAtFunction add the logic to switch the index properties of the two elements.
Then, when you fetch the entities, you add a predicate to your request, to sort the elements by the index property.
let fetchRequest = NSFetchRequest<EntityName>(entityName: "EntityName")
let sortDescripor = NSSortDescriptor(key: "index", ascending: true)
fetchRequest.sortDescriptors = [sortDescripor]
Then execute fetchRequest as you normally would, and assign the resulting array to the UICollectionView's Datasource.

how to pass image and label from one viewController to tableViewCell swift?

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

Send array from custom cell to another view controller

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

Unable to display array values on drop down menu

I am trying to code a drop down menu where I try to get an array to be displayed on a UITableView when a button is pressed. However, the entire mechanism works without having the values displayed. I am able to see the cell borders and scroll but no values can be seen :( Appreciate any help!
(My code)
import UIKit
class MainViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var dropDownButton: UIButton!
var fruityList = ["Apple", "Orange", "Pear", "Banana", "Peach"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.isHidden = true
}
#IBAction func dropDownButtonPressed(_ sender: Any) {
if tableView.isHidden {
animate(toggle: true)
} else {
animate(toggle: false)
}
}
func animate(toggle:Bool) {
if toggle {
UIView.animate(withDuration: 0.3) {
self.tableView.isHidden = false
}
} else {
UIView.animate(withDuration: 0.3) {
self.tableView.isHidden = true
}
}
}
}
extension MainViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fruityList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = fruityList[indexPath.row]
return cell
}
}

How to make a button, which adds new row with array data in TableView inside ViewController(they are not separate view controllers!)?

I am making a game using swift, and I want to make a history of answers. But the problem is Xcode tells thread1 exc_bad_instruction when I click button "addResult". Here is the code. Before launching the simulator and even after launching there is no error shown, however, when I click the "addResult" button the app crashes.
class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var choice1Text: UITextField!
#IBOutlet weak var resultLabel: UILabel!
#IBOutlet weak var choice2Text: UITextField!
#IBOutlet var mytableView: UITableView! {
didSet {
mytableView.dataSource = self
}
}
var items: [ResultlistItem]
required init?(coder aDecoder: NSCoder) {
items = [ResultlistItem]()
let row0item = ResultlistItem()
row0item.text = "Yes"
items.append(row0item)
let row1item = ResultlistItem()
row1item.text = "No"
items.append(row1item)
super.init(coder: aDecoder)
}
}
#IBAction func addResult(sender: AnyObject) {
let item = ResultlistItem()
item.text = "new one"
items.append(item)
mytableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Resultitem", for: indexPath)
let item = items[indexPath.row]
configureText(for: cell, with: item)
return cell
}
func configureText(for cell: UITableViewCell, with item: ResultlistItem) {
let label = cell.viewWithTag(1000) as! UILabel
label.text = item.text
}

Resources