Is there a way to get the value from a text filed in a table view cell to use it in another table view cell? - ios

I'm building an iOS e-commerce app which sells shoe products. This question is about the Checkout screen which is a UITableViewController to collect billing information of the user and save it in Firebase.
Below UITableViewController contains two custom UITableView cells. The first cell contains some text fields to get billing information(Email, Card Number, Expiration Date and CVC) from the user, while the second cell below that contains a submit button to save them in Firebase.
My requirement is to get the billing information from the user and save it in Firebase when clicking the Submit button. (Text fields and submit button are in two separate UITableView cells)
Could you please help me with this. Please find below code snippets.
CheckoutViewController.swift
class CheckoutTableViewController: UITableViewController {
// MARK: - Properties
var shoes : [Shoe]! {
didSet {
tableView.reloadData()
}
}
// MARK: - Structs
struct Storyboard {
static let billingInfoCell = "billingInfoCell"
static let submitButtonCell = "submitButtonCell"
}
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.billingInfoCell, for: indexPath) as! BillingInfoTableViewCell // Contains billing information text fields
return cell
} else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.submitButtonCell, for: indexPath) as! SubmitButtonTableViewCell // Contains Submit button
return cell
} else {
return UITableViewCell()
}
}
}
BillingInfoTableViewCell.swift
class BillingInfoTableViewCell: UITableViewCell {
// MARK: - IBOutlets
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var cardNumberTextField: UITextField!
#IBOutlet weak var expirationDataTextField: UITextField!
#IBOutlet weak var securityNumberTextField: UITextField!
}
SubmitButtonTableViewCell.swift
class SubmitButtonTableViewCell: UITableViewCell {
// MARK: - IBActions
#IBAction func submitOrderButtonTapped(_ sender: UIButton) {
print("Submit button tapped!")
}
}

Please follow the below steps.
Make the outlet of UITableView
#IBOutlet weak var tableView: UITableView!
Make static UITableviewCell
lazy var cellBillingInfo = tableView.dequeueReusableCell(withIdentifier: Storyboard.billingInfoCell) as! BillingInfoTableViewCell
lazy var cellSubmit = tableView.dequeueReusableCell(withIdentifier: Storyboard.submitButtonCell) as! SubmitButtonTableViewCell
Add target for submit button as below.
cellSubmit.btnSumit.addTarget(self, action: #selector(submitOrderButtonTapped(_:).tou), for: .touchUpInside)
Define submit button method
#objc func submitOrderButtonTapped(_ sender: UIButton) {
print(cellBillingInfo.emailTextField.text)
print(cellBillingInfo.cardNumberTextField.text)
print(cellBillingInfo.expirationDataTextField.text)
print(cellBillingInfo.securityNumberTextField.text)
}
Final Code:
class ViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
// MARK: - Properties
lazy var cellBillingInfo = tableView.dequeueReusableCell(withIdentifier: Storyboard.billingInfoCell) as! BillingInfoTableViewCell
lazy var cellSubmit = tableView.dequeueReusableCell(withIdentifier: Storyboard.submitButtonCell) as! SubmitButtonTableViewCell
var shoes : [Shoe]! {
didSet {
tableView.reloadData()
}
}
// MARK: - Structs
struct Storyboard {
static let billingInfoCell = "billingInfoCell"
static let submitButtonCell = "submitButtonCell"
}
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Data source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
return cellBillingInfo
} else if indexPath.row == 1 {
cellSubmit.btnSumit.addTarget(self, action: #selector(submitOrderButtonTapped(_:).tou), for: .touchUpInside)
return cellSubmit
} else {
return UITableViewCell()
}
}
#objc func submitOrderButtonTapped(_ sender: UIButton) {
print(cellBillingInfo.emailTextField.text)
print(cellBillingInfo.cardNumberTextField.text)
print(cellBillingInfo.expirationDataTextField.text)
print(cellBillingInfo.securityNumberTextField.text)
}
}
class SubmitButtonTableViewCell: UITableViewCell {
#IBOutlet weak var btnSumit: UIButton!
}

Related

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
}

In swift, how to manage two buttons in same custom tableview cell?

I am trying to manage two buttons in same custom tableview cell.
Added two buttons named Yes and No. If yes button is selected the No button will be inactive and Yes button became active.
Here is the image what I need
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell") as! TableViewCell
cell.yesButton.tag = 101
cell.noButton.tag = 102
cell.yesButton.addTarget(self, action: #selector(buttonClicked(sender:)), for: UIControl.Event.touchUpInside)
cell.noButton.addTarget(self, action: #selector(buttonClicked(sender:)), for: UIControl.Event.touchUpInside)
return cell
}
#objc func buttonClicked(sender: AnyObject) {
let buttonPosition = (sender as AnyObject).convert(CGPoint.zero, to: tableList)
let indexPath = tableList.indexPathForRow(at: buttonPosition)
if sender.tag == 101 {
if indexPath != nil {
print("Cell indexpath = \(String(describing: indexPath?.row))")
}
}
if sender.tag == 102 {
if indexPath != nil {
print("Cell indexpath = \(String(describing: indexPath?.row))")
}
}
}
Create a model to main the state of yesButton and noButton for each tableViewCell, i.e.
class Model {
var isYesSelected = false
var isNoSelected = false
}
Create a custom UITableViewCell with Outlets of yesButton and noButton.
Create a single #IBAction for both the buttons and handle their UI based on which button is tapped.
Also, use a buttonTapHandler to identify the row in which the button is tapped. It will be called everytime a button is tapped. We'll be setting this when creating the instance of TableViewCell in tableView(_:cellForRowAt:).
class TableViewCell: UITableViewCell {
#IBOutlet weak var yesButton: UIButton!
#IBOutlet weak var noButton: UIButton!
var buttonTapHandler: (()->())?
var model: Model?
override func prepareForReuse() {
super.prepareForReuse()
yesButton.backgroundColor = .gray
noButton.backgroundColor = .gray
}
func configure(with model: Model) {
self.model = model
self.updateUI()
}
#IBAction func onTapButton(_ sender: UIButton) {
model?.isYesSelected = (sender == yesButton)
model?.isNoSelected = !(sender == yesButton)
self.updateUI()
}
func updateUI() {
yesButton.backgroundColor = (model?.isYesSelected ?? false) ? .green : .gray
noButton.backgroundColor = (model?.isNoSelected ?? false) ? .green : .gray
}
}
UITableViewDataSource's tableView(_:cellForRowAt:) method goes like,
let numberOfCells = 10
var models = [Model]()
override func viewDidLoad() {
super.viewDidLoad()
(0..<numberOfCells).forEach { _ in
self.models.append(Model())
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberOfCells
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! TableViewCell
cell.configure(with: models[indexPath.row])
cell.buttonTapHandler = {
print(indexPath.row)
}
return cell
}
To get the totalPoints, count the models with isYesSelected = true, i.e.
let totalPoints = models.reduce(0) { (result, model) -> Int in
if model.isYesSelected {
return result + 1
}
return 0
}
print(totalPoints)
Get that Button using your Tag like below and after that, you can change the value as per you want.
var tmpButton = self.view.viewWithTag(tmpTag) as? UIButton
Simple 3 step process...!!
Define Model Class
Prepare tableView Cell & handle actions
Set up tableView in view controller
Let's start implementation:
1) Define Model Class
In UI, we have a information like question & it's answer (Yes/No). So design model respectively.
//MARK:- Class Declaration -
class Question {
let questionText: String
var answerState: Bool?
init(question: String) {
self.questionText = question
}
}
2. Prepare tableView Cell & handle actions
Create a custom tableView cell with Question Label, Yes Button & No Button. Link that view with respected #IBOutlets & #IBActions.
import UIKit
class TableViewCell: UITableViewCell {
#IBOutlet weak var questionLabel: UILabel!
#IBOutlet weak var yesButton: UIButton!
#IBOutlet weak var noButton: UIButton!
var question: Question?
var toggle: Bool? {
didSet {
question?.answerState = toggle
//Do buttons operations like...
if let isToggle = toggle {
yesButton.backgroundColor = isToggle ? .green : .gray
noButton.backgroundColor = isToggle ? .gray : .green
} else {
yesButton.backgroundColor = .gray
noButton.backgroundColor = .gray
}
}
}
func prepareView(forQuestion question: Question) {
self.question = question
questionLabel.text = question.questionText
toggle = question.answerState
}
//Yes Button - IBAction Method
#IBAction func yesButtonTapped(_ sender: UIButton) {
toggle = true
}
//No Button - IBAction Method
#IBAction func noButtonTapped(_ sender: UIButton) {
toggle = false
}
}
3. Set up tableView in view controller
class ViewController: UIViewController {
//Prepare questions model array to design our tableView data source
let arrQuestions: [Question] = [Question(question: "Do you speak English?"), Question(question: "Do you live in Chicago?")]
}
//MARK:- UITableView Data Source & Delegate Methods -
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrQuestions.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let tableViewCell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as? TableViewCell else {
return UITableViewCell()
}
tableViewCell.prepareView(forQuestion: arrQuestions[indexPath.row])
return tableViewCell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80.0
}
}
Create basic tableView and configure dataSource functions
Create tableView cell with two buttons
Create cell class with buttons outlets and actions
Result of this code
Enjoy!

Table view cell elements not able to click and get data

I have one table view and inside that i placed one main view. And inside that main view i placed one button.And when ever use click on my cell button. I need to get the cell title label.This is what i need. But i tried following below code. Not sure what i am missing out. It not at all calling my cell.add target line.
Code in cell for row at index:
cell.cellBtn.tag = indexPath.row
cell.cellBtn.addTarget(self, action:#selector(self.buttonPressed(_:)), for:.touchUpInside)
#objc func buttonPressed(_ sender: AnyObject) {
print("cell tap")
let button = sender as? UIButton
let cell = button?.superview?.superview as? UITableViewCell
let indexPath = tableView.indexPath(for: cell!)
let currentCell = tableView.cellForRow(at: indexPath!)! as! KMTrainingTableViewCell
print(indexPath?.row)
print(currentCell.cellTitleLabel.text)
}
I even added a breakpoint, still it not at calling my cell.addTarget line
Tried with closure too. In cell for row at index:
cell.tapCallback = {
print(indexPath.row)
}
In my table view cell:
var tapCallback: (() -> Void)?
#IBAction func CellBtndidTap(_ sender: Any) {
print("Right button is tapped")
tapCallback?()
}
Here that print statement is getting print in console.
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var list = [String]()
#IBOutlet weak var tableView: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return list.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyTableViewCell
cell.saveButton.tag = indexPath.row
//cell.saveButton.accessibilityIdentifier = "some unique identifier"
cell.tapCallback = { tag in
print(tag)
}
return cell
}
}
class MyTableViewCell: UITableViewCell {
// MARK: - IBOutlets
#IBOutlet weak var saveButton: UIButton!
// MARK: - IBActions
#IBAction func saveTapped(_ sender: UIButton) {
tapCallback?(sender.tag)
}
// MARK: - Actions
var tapCallback: ((Int) -> Void)?
}
Actually this is not a good programming practice to add the button (which contains in table view cell) target action in view controller. We should follow the protocol oriented approach for it. Please try to under stand the concept.
/*This is my cell Delegate*/
protocol InfoCellDelegate {
func showItem(item:String)
}
/*This is my cell class*/
class InfoCell: UITableViewCell {
//make weak reference to avoid the Retain Cycle
fileprivate weak var delegate: InfoCellDelegate?
//Outlet for views
#IBOutlet var showButton: UIButton?
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
//This is the public binding function which will bind the data & delegate to cell
func bind(with: DataModel?, delegate: InfoCellDelegate?, indexPath: IndexPath) {
//Now the bind the cell with data here
//.....
//Assign the delegate
self.delegate = delegate
}
//Button action
#IBAction func rowSelected(sender: UIButton) {
self.delegate?.showItem(item: "This is coming from cell")
}
}
/*Now in your ViewController you need to just confirm the InfoCellDelegate & call the bind function*/
class ListViewController: UIViewController {
//Views initialisation & other initial process
}
//Table view Delegate & Data source
extension ListViewController: UITableViewDataSource, UITableViewDelegate {
/**
Configure the table views
*/
func configureTable() {
//for item table
self.listTable.register(UINib.init(nibName: "\(InfoCell.classForCoder())", bundle: nil), forCellReuseIdentifier: "\(InfoCell.classForCoder())")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "InfoCell") as! InfoCell
cell.bind(with: DataModel, delegate: self, indexPath: indexPath)
return cell
}
}
extension ListViewController: InfoCellDelegate {
func showItem(item) {
print(item)
}
}

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

Update model through UIButton within a UITableViewCell

In MainVC.swift I'm capturing the tag of my custom "PlayerCell". I want to press theincreaseBtn (UIButton) which will increment the playerLbl.text (UILabel) by one but also update my model (PlayerStore.player.playerScore: Int)
Main.swift:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "PlayerCell", for: indexPath) as? PlayerCell {
let player = players[indexPath.row]
cell.updateUI(player: player)
cell.increaseBtn.tag = indexPath.row
cell.decreaseBtn.tag = indexPath.row
return cell
} else {
return UITableViewCell()
}
}
PlayerCell.swift
class PlayerCell: UITableViewCell {
#IBOutlet weak var playerLbl: UILabel!
#IBOutlet weak var increaseBtn: UIButton!
#IBOutlet weak var decreaseBtn: UIButton!
#IBOutlet weak var scoreLbl: UILabel!
#IBOutlet weak var cellContentView: UIView!
func updateUI(player: Player){
playerLbl.text = player.playerName
scoreLbl.text = "\(player.playerScore)"
cellContentView.backgroundColor = player.playerColor.color
}
#IBAction func increaseBtnPressed(_ sender: AnyObject) {
let tag = sender.tag
// TODO: send this tag back to MainVC?
}
I would use the delegate pattern in this case. Create a protocol that Main.swift implements, and that PlayerCell.swift uses as an optional property. So for example:
protocol PlayerIncrementor {
func increment(by: Int)
func decrement(by: Int)
}
Then use an extension on Main.swift to implement this protocol
extension Main: PlayerIncrementor {
func increment(by: int) {
//not 100% what you wanted to do with the value here, but this is where you would do something - in this case incrementing what was identified as your model
PlayerStore.player.playerScore += by
}
}
Inside of PlayerCell.swift, add a delegate property and call the delegate increment method in your #IBAction
class PlayerCell: UITableViewCell {
var delegate: PlayerIncrementor?
#IBOutlet weak var increaseBtn: UIButton!
#IBAction func increaseBtnPressed(_ sender: AnyObject) {
let tag = sender.tag
//call the delegate method with the amount you want to increment
delegate?.increment(by: tag)
}
Lastly - to make it all work, assign Main as the delegate to the PlayerCell UITableViewCell.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "PlayerCell", for: indexPath) as? PlayerCell {
//self, in this case is Main - which now implements PlayerIncrementor
cell.delegate = self
//etc

Resources