Alex Ghita
Alex Ghita

Reputation: 19

Plus and minus buttons for a shopping app in swift

I've got a problem. I can't find a way to make these buttons work properly and I need some help.

I'm trying to make a app for a restaurant and I don't know how to make the plus and the minus buttons work. I extract data from Firebase (the name and the price for the product). I have a label for amount. Click plus amount increase, click minus amount decrease.

This is how it looks like

Here is the code from my viewController:

import UIKit
import Firebase
import FirebaseDatabase

class foodListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{

@IBOutlet weak var plus: UIButton!
@IBOutlet weak var foodTableView: UITableView!
var ref:DatabaseReference?
var databaseHandle: DatabaseHandle?
var foodData = [food]()
var stats = [Buy]()

override func viewDidLoad() {
    super.viewDidLoad()

    foodTableView.delegate = self
    foodTableView.dataSource = self
    foodTableView.backgroundView = UIImageView(image: UIImage(named: "bg-general.png"))
    foodTableView.allowsSelection = false
    foodTableView.separatorStyle = .none

    //Set the firebase reference
    ref = Database.database().reference()

    //Retrieve the data and listen for changes
ref?.child("inventory").child("food").observe(.childAdded, with: { (snapshot) in
   /*    if let dict = snapshot.value as? [String: AnyObject] {
        let foods = food()
            foods.setValuesForKeys(dict)
            print(foods.FirstName!)
            //self.foodTableView.reloadData()
    }*/
    print(snapshot)
    if let dictionary = snapshot.value as? [String: AnyObject] {
        let foods = food()
       // foods.setValuesForKeys(dictionary)
        foods.title = dictionary["title"] as? String
        foods.amount = dictionary["amount"] as? String
        foods.price = dictionary["price"] as? Double
        foods.category = dictionary["category"] as? String
        foods.id = dictionary["id"] as? String

        self.foodData.append(foods)


       DispatchQueue.main.async {
            print("BlaBlaBla")
            self.foodTableView.reloadData()
       }
      //  print(foods.title!,foods.amount!,foods.price!,foods.category!,foods.id!)

    }

    })

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return foodData.count
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 140;
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "FoodCell", for: indexPath)

    let food = foodData[indexPath.row]
    // Food and price
    let titleLabel = cell.viewWithTag(1) as! UILabel
    let priceLabel = cell.viewWithTag(2) as! UILabel
    let cantitateLabel = cell.viewWithTag(3) as! UILabel

    //Labels text size
   // titleLabel.font = UIFont(name: "Times New Roman-Bold", size: 30)
  //  priceLabel.font = UIFont(name: "Times New Roman-Bold", size: 17.0)
  //  cantitateLabel.font = UIFont(name: "Times New Roman-Bold", size: 17.0)



    titleLabel.text = food.title
    let numberFormatter = NumberFormatter()
    numberFormatter.numberStyle = .decimal
    priceLabel.text = numberFormatter.string(from: food.price! as NSNumber)! + " $"

    // Design for table
    cell.backgroundColor = UIColor.clear
    cell.contentView.backgroundColor = UIColor.clear
    let whiteRoundedView : UIView = UIView(frame: CGRect(x: 0, y: 10, width: self.view.frame.size.width, height: 70))
    whiteRoundedView.backgroundColor = UIColor.greenColor
    whiteRoundedView.layer.masksToBounds = false
    whiteRoundedView.layer.cornerRadius = 3.0
    whiteRoundedView.layer.shadowOffset = CGSize(width: -1, height: 1)
    whiteRoundedView.layer.shadowOpacity = 0.5
    cell.contentView.addSubview(whiteRoundedView)
    cell.contentView.sendSubview(toBack: whiteRoundedView)

    //Plus - Minus
    let pluss = cell.viewWithTag(4) as! UIButton
    let minuss = cell.viewWithTag(5) as! UIButton

    //pluss.addTarget(self, action: #selector(plusss(cantitate: amount)), for: .touchUpInside)
  //  minuss.addTarget(self, action: #selector(minusss(cantitate: amount)), for:. touchUpInside)



    return cell

}

}

Also, pressing plus will add my product to another viewcontroller which is for my order list. Pressing minus will decrease the amount and, when the amount is 0, it will delete my product from order list.

Thanks in advance.

Upvotes: 0

Views: 4768

Answers (2)

iOS Geek
iOS Geek

Reputation: 4855

This is how I have managed my two different button to act as stepper

My Array That stores the values which need to be updated

var meanValuesArray : [String] = ["","","0","0","0","1","1","",""]

Enum Function used to justify which task is to be Performed

//MARK: math Function Enum
/**
 This Enum is used to Detect do Add Math Operation or Subtract action is to be Performed
 */
enum mathFunction {
    /// When Addition is to done
    case Add
    /// When Subtraction is to be Done
    case Subtract
}

Cell For Row Method

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.addPropertyTableView.dequeueReusableCell(withIdentifier: "APStepperSwitch", for: indexPath) as! addPropertyWithStepperSwitch
        cell.staticImageView.image = self.leftImagesArray[indexPath.row]
        cell.propertyDetailLabel.text = self.leftValueArray[indexPath.row]
        cell.propertyStepperLabel.text = self.meanValuesArray[indexPath.row]

        /// Adding Button Handlers
        cell.propertyPlusButton.addTarget(self, action: #selector(AddingPropertyVC.plusButtonHandler(sender:)), for: UIControlEvents.touchUpInside)
        cell.propertyMinusButton.addTarget(self, action: #selector(AddingPropertyVC.minusButtonHandler(sender:)), for: UIControlEvents.touchUpInside)
        return cell
    }

Button Actions

@objc func minusButtonHandler(sender: UIButton) {
        /// Getting The Button Position Which is clicked
        let buttonPosition : CGPoint = sender.convert(CGPoint.zero, to: self.addPropertyTableView)

        /// Getting Index Path From Button Location
        let indexPath : IndexPath = self.addPropertyTableView.indexPathForRow(at: buttonPosition)!

        /// Extracting and Updating my current Order Value Either + or -
        self.meanValuesArray[indexPath.row] = AFWrapperClass.compareStringValue(currentValue: self.meanValuesArray[indexPath.row], limit: 20, toDo: .Subtract)

        /// Reloading Table
        self.addPropertyTableView.reloadData()
    }

    @objc func plusButtonHandler(sender: UIButton) {
        /// Getting The Button Position Which is clicked
        let buttonPosition : CGPoint = sender.convert(CGPoint.zero, to: self.addPropertyTableView)

        /// Getting Index Path From Button Location
        let indexPath : IndexPath = self.addPropertyTableView.indexPathForRow(at: buttonPosition)!

        /// Extracting and Updating my current Order Value Either + or -
        self.meanValuesArray[indexPath.row] = AFWrapperClass.compareStringValue(currentValue: self.meanValuesArray[indexPath.row], limit: 20, toDo: .Add)

        /// Reloading Table
        self.addPropertyTableView.reloadData()
    }

Main Stepper Function

class AFWrapperClass : NSObject {
        //MARK: Fucntion used to comapre and update value
        /**
         This function is used to update stepper values
         - parameter currentValue : Current Value in Array
         - parameter limit : Maximum Value that can be used as stepper+1
         - parameter toDo : tells need to perform Add or subtract
         */
        class func compareStringValue(currentValue:String, limit:Int, toDo : mathFunction) -> String {
            var current : Int = Int(currentValue)!
            if (current <= limit) && (current >= 0) {
                if toDo == .Add {
                    if current == limit {
                        return String(current)
                    }
                    else{
                        current += 1
                        return String(current)
                    }
                }
                else {
                    if current == 0 {
                        return String(current)
                    }
                    else {
                        current -= 1
                        return String(current)
                    }
                }
            }
            else {
                return String(current)
            }
        }
    }

Upvotes: 0

Alejandro Artavia
Alejandro Artavia

Reputation: 11

You need an IBAction for such buttons... I recommend you to have a prototype tableViewCell with the buttons and labels and handle the actions in the corresponding view controller.

Upvotes: 0

Related Questions