passing data from button in cell to another tableview? - ios

how do I pass data from button in menu tableview to cart tableview?
would I segue it, use closures, protocol/delegates, something else?
Im having trouble passing data from my AddtoCart Button in my MenuViewController to CartViewController
the objective is to put items in the CartVC when the ATC button is pressed in the MenuCell
The CartButton on the NavBar in the MenuVC segues to the CartVC when pressed
The ATC button in the cell passes all the selected cells data to the cartVC (image, name, category, weight & price)
Im using Cloud Firestore to post data to populate my VC cells
I have tried so many different solutions posted on stack and still nothing seems to works, I have been stuck on this for almost 2 weeks... any help would be much much appreciated
import UIKit
import SDWebImage
import Firebase
class MenuCell: UITableViewCell {
weak var items: Items!
#IBOutlet weak var name: UILabel!
#IBOutlet weak var category: UILabel!
#IBOutlet weak var productImage: UIImageView!
#IBOutlet weak var weight: UILabel!
#IBOutlet weak var price: UILabel!
#IBOutlet weak var addToCart: RoundButton!
func configure(withItems items: Items) {
name.text = items.name
category.text = items.category
image.sd_setImage(with: URL(string: items.image))
price.text = items.price
weight.text = items.weight
self.items = items
}
}
import UIKit
import Firebase
import FirebaseFirestore
class MenuViewController: UITableViewController {
#IBOutlet weak var cartButton: BarButtonItem!!
#IBOutlet weak var tableView: UITableView!
var itemSetup: [Items] = []
override func viewDidLoad() {
super.viewDidLoad()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemSetup.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "MenuCell") as? MenuCell else { return UITableViewCell() }
cell.configure(withItem: itemSetup[indexPath.row])
return cell
}
}
extension CartViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Cart.currentCart.cartItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CartCell", for: indexPath) as! CartCell
let cart = Cart.currentCart.CartItems[indexPath.row]
cell.lblWeight.text = cart.items.weight
cell.lblMealName.text = "\(cart.items.category): \(cart.items.name)"
cell.lblSubTotal.text = "$\(cart.items.price)"
cell.imageUrl // can't figure out how to pass image
return cell
}
}
class CartItem {
var items: Items
init(items: Items) {
self.items = items
}
}

The first thing I would do is get rid of CartItem - It doesn't seem to be doing anything except wrapping an Items instance, and you have some confusion in your code as to whether you are using CartItem or Items (I would probably also rename Items to Item - singular).
class Cart {
static let currentCart = Cart()
var cartItems = [Items]()
}
To get the "add to cart" action from your cell you can use a delegation pattern or provide a closure to handle the action. I will use a closure
class MenuCell: UITableViewCell {
#IBOutlet weak var name: UILabel!
#IBOutlet weak var category: UILabel!
#IBOutlet weak var productImage: UIImageView!
#IBOutlet weak var weight: UILabel!
#IBOutlet weak var price: UILabel!
#IBOutlet weak var addToCart: RoundButton!
var addActionHandler: (() -> Void)?
func configure(withItems items: Items) {
name.text = items.name
category.text = items.category
image.sd_setImage(with: URL(string: items.image))
price.text = items.price
weight.text = items.weight
}
#IBAction func addTapped(_ sender: UIButton) {
self.addActionHandler?()
}
}
Now, in your menu cellForRowAt you can provide the action handler:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MenuCell") as! MenuCell // Just crash at this point if there isn't a valid cell identifier configured
let item = itemSetup[indexPath.row]
cell.configure(withItem: item)
cell.addActionHandler = {
Cart.currentCart.items.append(item)
}
return cell
}
And that should be all you need to do - When you segue to the cart view controller, it will show the current contents of the cart.
Note that you could improve your cart data model somewhat by allowing it to have a quantity for each item and providing an add(item:) function that incremented the quantity if the item was in the cart

Related

tableview doesn't show anything?

I made sure that my cell identifier was correct I'm not too sure what the problem is. I've been rereading the code on this viewController and I'm not sure if I'm missing something or if there's a specific reason why my tableview isn't loading.
import UIKit
import JGProgressHUD
class BasketViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = footerView
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//MARK: TO DO CHECK IF USER IS LOGGED IN
loadBasketFromFirestore()
}
//MARK: VARS
var basket : basket?
var allItems : [Item] = []
var purchaseItemID : [String] = [] //holds id of items you want to purchase
var hud = JGProgressHUD(style: .dark)
//MARK: IBOUTLETS
#IBOutlet weak var totalPriceLabel: UILabel!
#IBOutlet weak var totalItemsInBasket: UILabel!
#IBOutlet weak var checkOutButton: UIButton!
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var footerView: UIView!
//MARK: IBACTIONS
#IBAction func checkOutButtonTapped(_ sender: Any) {}
//something is wrong with
//MARK: DOWNLOAD BASKET
private func loadBasketFromFirestore(){
//MARK: CHANGE 1234 TO A USER ID STRING
downloadBasketFromFirestore("1234") { (basket) in
self.basket = basket
self.getBasketItems()
}
}
private func getBasketItems(){
if (basket != nil) {
print("getting items")
downloadItems(_withIDS: basket!.itemID) { (allItems) in
self.allItems = allItems
self.tableView.reloadData()
}
} else { print("basket is nil")}
}
}
extension BasketViewController : UITableViewDataSource , UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "basketCell", for: indexPath) as! ITEMTableViewCell
cell.generateCellForITEMS(item: allItems[indexPath.row])
return cell
}
}

How would I be able to pass an image when data is passed from one View Controller to another?

How would I be able to show an image from HomeViewController to the CartViewController
I have the code setup in my cells to where the data passes from one VC to another,
Im trying to present the image when the data is passed
How would I be able to show the image when data is passed from the HomeVC to the CartVC after the atcBtn is pressed
all the data in my labels passes fine its just the image data that fails to pass
I have tried a few ways from stack but I still keep getting error codes on presenting the image in the CartVC
class CartViewController: UIViewController {
var items: Items!
#IBOutlet weak var cartTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
cartTableView.dataSource = self
cartTableView.delegate = self
}
}
extension CartViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Cart.currentCart.cartItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CartCell", for: indexPath) as! CartCell
let cart = Cart.currentCart.CartItems[indexPath.row]
cell.store.text = cart.items.store
cell.lblMealName.text = (cart.items.name)
cell.lblSubTotal.text = "$\(cart.items.cost)"
cell.imageUrl.image = cart.imageUrl // can't figure out how to get this to code to work since it is an Image to String issue
return cell
class CartCell: UITableViewCell {
#IBOutlet weak var lblMealName: UILabel!
#IBOutlet weak var imageUrl: UIImageView!
#IBOutlet weak var lblSubTotal: UILabel!
#IBOutlet weak var lblWeight: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
The code you posted doesn't quite match up:
In cellForRowAt in CartViewController, for example, you are using CartCell but your code is setting:
cell.store.text = cart.items.store
but there is no store label / property in your posted CartCell.
However, since you are doing very similar things with HomeCell class, just take the same approach for CartCell.
Something along these lines:
class CartCell: UITableViewCell {
#IBOutlet weak var lblMealName: UILabel!
#IBOutlet weak var imageUrl: UIImageView!
#IBOutlet weak var lblSubTotal: UILabel!
#IBOutlet weak var lblWeight: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func configure(withItems items: Items) {
//store.text = cart.items.store
lblMealName.text = (items.name)
lblSubTotal.text = "$\(items.cost)"
imageUrl.sd_setImage(with: URL(string: items.imageUrl))
}
}
and change `cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CartCell", for: indexPath) as! CartCell
let cart = Cart.currentCart.CartItems[indexPath.row]
//cell.store.text = cart.items.store
//cell.lblMealName.text = (cart.items.name)
//cell.lblSubTotal.text = "$\(cart.items.cost)"
//cell.imageUrl.image = cart.imageUrl // can't figure out how to get this to code to work since it is an Image to String issue
cell.configure(withItem: cart)
return cell
}
This appears to be where the problem is
cell.imageUrl.image = cart.imageUrl // can't figure out how to get
this to code to work since it is an Image to String issue
and as you noted, that code doesn't really make sense... If you're storing a url (a string) in your cart object, then you can't cast that to an image with cell.imageUrl.image, right?
You would need to assign it to the url
cell.imageUrl = cart.imageUrl
Of course that will just pass the url to the cell. The cell would then need some intelligence to get that associated image from the url.
Some pseudo code for your CartCell class...
cell.store.text = cart.items.store
cell.lblMealName.text = (cart.items.name)
cell.lblSubTotal.text = "$\(cart.items.cost)"
cell.setImageUrlAndDisplayImage( cart.imageUrl )
and then the function in the CartCell class
func setImageUrlAndDisplayImage( imageUrl: URL) {
self.setImage(with: URL(string: imageUrl))
}
or of course, you could just assign the image directly to the CartCell image property if it has one.
cell.store.text = cart.items.store
cell.lblMealName.text = (cart.items.name)
cell.lblSubTotal.text = "$\(cart.items.cost)"
cell.the_image = UIImage(with: URL(string: cart.imageUrl))
The above is just pseudo code since we don't know what you Cart class or CartCell class looks like.

How to pass data on button clicked in cell to another tableview?

First: How would I be able to pass data from the ItemVC Cell to the CartVC on button Clicked (Add To Cart Button(ATC)) in the selected cell, since I am no trying to use didSelectRowAt to pass the data to the CartVC. but the ATC btn to pass the cells data to the CartVC
my Segue from the ItemVC to the CartVC is in the BarButtonItem(cartBtn) so I dont want to jump to the CartVc when pressing the ATC button but only pass selected items data to CartVC when the ATC is pressed
Second how would I be able to pass the increment/decrement value in lblQty to to the CartVC when the ATC is pressed as well to be able to present a more accurate Subtotal
import UIKit
import SDWebImage
import Firebase
class ItemCell: UITableViewCell {
weak var items: Items!
#IBOutlet weak var name: UILabel!
#IBOutlet weak var category: UILabel!
#IBOutlet weak var productImage: UIImageView!
#IBOutlet weak var weight: UILabel!
#IBOutlet weak var price: UILabel!
#IBOutlet weak var lblQty: UILabel!
#IBOutlet weak var addToCart: RoundButton!
#IBOutlet weak var plusBtn: RoundButton!
#IBOutlet weak var minusBtn: RoundButton!
func configure(withItems : Items) {
name.text = product.name
category.text = items.category
image.sd_setImage(with: URL(string: items.image))
price.text = items.price
weight.text = items.weight
}
}
import UIKit
import Firebase
import FirebaseFirestore
class ItemViewController: UITableViewController {
#IBOutlet weak var cartBtn: BarButtonItem!!
#IBOutlet weak var tableView: UITableView!
var itemSetup: [Items] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
fetchItems { (items) in
self.itemSetup = items.sorted
self.tableView.reloadData()
}
}
func fetchItems(_ completion: #escaping ([Items]) -> Void) {
// -** FireStore Code **-
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as? CartViewController {
vc.items = self.itemSetup
}
}
#objc func plusItem(_ sender: UIButton) {
// -** increase Qty Code **-
}
//Function to decrement item count
#objc func minusItem(_ sender: UIButton) {
// -** decrease Qty Code **-
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemSetup.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell") as? ItemCell else { return UITableViewCell() }
cell.configure(withItem: itemSetup[indexPath.row])
cell.lblQty.text = "\(self.imageSetup[indexPath.row].count)"
cell.plusBtn.tag = indexPath.row
cell.plusBtn.addTarget(self, action: #selector(self.plusItem(_:)), for: .touchUpInside)
cell.minusBtn.tag = indexPath.row
cell.minusBtn.addTarget(self, action: #selector(self.minusItem(_:)), for: .touchUpInside)
return cell
}
}
class CartViewController: UIViewController {
var items: Items!
#IBOutlet weak var cartTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
cartTableView.dataSource = self
cartTableView.delegate = self
}
}
extension CartViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Cart.currentCart.cartItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CartCell", for: indexPath) as! CartCell
let cart = Cart.currentCart.CartItems[indexPath.row]
cell.qty.text = "\(cart.qty)"
cell.lblMealName.text = "\(cart.items.category): \(cart.items.name)"
cell.lblSubTotal.text = "$\(cart.items.price1 * Float(cart.qty))"
cell.imageUrl // can't figure out how to pass image
return cell
}
}
import Foundation
class CartItem {
var items: Items
var qty: Int
init(items: Items, qty: Int) {
self.items = items
self.qty = qty
}
}
class Cart {
static let currentCart = Cart()
var cartItems = [CartItem]()
}
Just create a protocol to create a delegate and assign it to your cart class when the cell is initialized
protocol ItemCellDelegate {
func itemCell(didTapButton button: UIButton)
}
Then have a delegate property in the ItemCell
class ItemCell {
weak var delegate: ItemCellDelegate?
...
// Then call the delegate method when the buttons is tapped.
func buttonTapped() {
delegate?.itemCell(didTapButton: theCellsButton)
}
}
Then make your Cart conform to the delegate
extension Cart: ItemCellDelegate {
func itemCell(didTapButton button: UIButton) {
// Do you stuff with button, or any other data you want to pass in
}
}
Then set the delegate before the cell is returned.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CartCell", for: indexPath) as! CartCell
let cart = Cart.currentCart.CartItems[indexPath.row]
cell.qty.text = "\(cart.qty)"
cell.lblMealName.text = "\(cart.items.category): \(cart.items.name)"
cell.lblSubTotal.text = "$\(cart.items.price1 * Float(cart.qty))"
cell.delegate = Cart.currentCart //You should rename this static var to just 'current'
return cell
}

Deleting a UITableView cell in a specific section

There is a task. Each cell contains a button by clicking which you want to delete this cell. The problem is that sections are used to delineate the entire list by category. The data I take from Realm DB. removal must occur under two conditions because the name is repeated, so you need to consider the name from the label and the name of the section. I will be very grateful for the sample code with comments.
import UIKit
import RealmSwift
class PurchesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var purchesTableView: UITableView!
let manage = ManagerData()
override func viewDidLoad() {
super.viewDidLoad()
purchesTableView.delegate = self
purchesTableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
purchesTableView.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return manage.loadPurchases().0.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return manage.loadPurchases().0[section]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return manage.loadPurchases().1[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "purchesCell", for: indexPath) as! CustomPurchesTableViewCell
cell.productLabel.text = manage.loadPurchases().1[indexPath.section][indexPath.row]
cell.weightProductLabel.text = manage.loadPurchases().2[indexPath.section][indexPath.row]
cell.weightNameLabel.text = manage.loadPurchases().3[indexPath.section][indexPath.row]
// cell.boughtButton.addTarget(self, action: #selector(removeProduct), for: .touchUpInside)
return cell
}
}
class CustomPurchesTableViewCell: UITableViewCell {
#IBOutlet weak var boughtButton: UIButton!
#IBOutlet weak var productLabel: UILabel!
#IBOutlet weak var weightProductLabel: UILabel!
#IBOutlet weak var weightNameLabel: UILabel!
#IBAction func removePurches(_ sender: Any) {
print("remove")
}
}
method for get data
func loadPurchases() -> ([String], Array<Array<String>>, Array<Array<String>>, Array<Array<String>>) {
var sections: [String] = []
var product = Array<Array<String>>()
var weight = Array<Array<String>>()
var nameWeight = Array<Array<String>>()
let realm = try! Realm()
let data = realm.objects(Purches.self)
for item in data {
if sections.contains(item.nameDish) == false {
sections.append(item.nameDish)
}
}
for a in sections {
var productArr = Array<String>()
var weightArr = Array<String>()
var nameWeightArr = Array<String>()
for prod in data {
if a == prod.nameDish {
productArr.append(prod.product)
weightArr.append(prod.weight)
nameWeightArr.append(prod.nameWeigh)
}
}
product.append(productArr)
weight.append(weightArr)
nameWeight.append(nameWeightArr)
}
return (sections, product, weight, nameWeight)
}
Index path you will get in cell class
Index path have two property section and row for table view
Now you can create on more method in Controller class and assign to a variable to every cell or you can use editAction provided by table view for delete
in order to get number section and row you need create IBOutlet in custom cell and on ViewController class is created addTarget for your button.
Example code at the bottom.
import UIKit
import RealmSwift
class PurchesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var purchesTableView: UITableView!
let manage = ManagerData()
//... more code ...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "purchesCell", for: indexPath) as! CustomPurchesTableViewCell
cell.productLabel.text = manage.loadPurchases().1[indexPath.section][indexPath.row]
cell.weightProductLabel.text = manage.loadPurchases().2[indexPath.section][indexPath.row]
cell.weightNameLabel.text = manage.loadPurchases().3[indexPath.section][indexPath.row]
cell.boughtButton.addTarget(self, action: #selector(removePurches(_:)), for: .touchUpInside)
return cell
}
#objc func removePurches(_ sender: UIButton) {
let position: CGPoint = sender.convert(CGPoint.zero, to: purchesTableView)
let indexPath: IndexPath! = self.purchesTableView.indexPathForRow(at: position)
print("indexPath.row is = \(indexPath.row) && indexPath.section is = \(indexPath.section)")
purchesTableView.deleteRows(at: [indexPath], with: .fade)
}
}
and custom class CustomPurchesTableViewCell for cell
class CustomPurchesTableViewCell: UITableViewCell {
#IBOutlet weak var boughtButton: UIButton! // you button for press
#IBOutlet weak var productLabel: UILabel!
#IBOutlet weak var weightProductLabel: UILabel!
#IBOutlet weak var weightNameLabel: UILabel!
}

How to modify the properties of only one custom cell of a table view?

I want to have a table view cell that contains a button that increments a label by 1 everytime that button is pressed. So if the button is pressed, the label displays: "1,2,3,4", etc. And I want each cell row to be independent from each other, meaning I only want the increment button in cell row 3 to modify the label of cell row 3 and same for cell row 4 and so on.
However my current code functionality does the following:
When I press the increment button it changes the label for all cells not just the label the button is pressed in (I don't want this).
When I scroll the table view all the labels change even when I haven't pressed the button in that row (I want don't want this either, I only want the label to change if its corresponding increment button has been pressed).
Can anyone help get my code or help me construct some code to help me achieve my goals?
Thanks in advance all help is highly appreciated!
My code:
import UIKit
var bookieFlavors = ["Chocolate Chip", "Sugar w/o icing", "Sugar w/ icing", "Peanut Butter", "Honey", "Shortbread", "Ginger", "Double Chocolate", "Macadamie Nut", "Oatmeal Raisin", "Snickerdoodle"]
var labelAmount = Int()
class FlavorsController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var flavorTable: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return bookieFlavors.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! FlavorTableCell
//flavor label configuration
cell.flavorLabel.text = bookieFlavors[indexPath.row]
//amount configuration
cell.bookieAmount.text = "= \(amount)"
return cell
class FlavorTableCell: UITableViewCell {
#IBOutlet weak var flavorLabel: UILabel!
#IBOutlet weak var bookieButton: UIButton!
#IBAction func bookieButton(_ sender: UIButton) {
for _ in 1...15 {
bookieAmount.text = "= \(String(describing: amount))"
}
labelAmount += 1
}
#IBOutlet weak var bookieAmount: UILabel!
You can not add button action in the tableview cell to do this. Please check below code for the solution.
import UIKit
class FlavorsController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var bookieFlavors = ["Chocolate Chip", "Sugar w/o icing", "Sugar w/ icing", "Peanut Butter", "Honey", "Shortbread", "Ginger", "Double Chocolate", "Macadamie Nut", "Oatmeal Raisin", "Snickerdoodle"]
var labelAmount = [Int]() // To keep track of the amount in each cell
#IBOutlet weak var flavorTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
for item in self.bookieFlavors {
self.labelAmount.append(0) //Initialise with default value
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return bookieFlavors.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! FlavorTableCell
//flavor label configuration
cell.flavorLabel.text = bookieFlavors[indexPath.row]
//amount configuration
cell.bookieAmount.text = "= \(self.labelAmount[indexPath.row])"
cell.bookieButton.tag = indexPath.row
cell.bookieButton.addTarget(self, action: #selector(bookieButton(_:)), for: .touchUpInside)
return cell
}
//To configure the button click and according changes
#IBAction func bookieButton(_ sender: UIButton) {
self.labelAmount[sender.tag] = self.labelAmount[sender.tag] + 1
let cell = self.flavorTable.cellForRow(at: IndexPath(row: sender.tag, section: 0)) as? FlavorTableCell
cell?.bookieAmount.text = "= \(self.labelAmount[sender.tag])"
}
}
class FlavorTableCell: UITableViewCell {
#IBOutlet weak var flavorLabel: UILabel!
#IBOutlet weak var bookieButton: UIButton!
#IBOutlet weak var bookieAmount: UILabel!
}

Resources