Home > database >  How to assign different actions for same UIButton?
How to assign different actions for same UIButton?

Time:09-16

while click on the button for the first time, the title of the button will get changed from "Add to Cart" to "Go to Cart". And from the next click the button will navigate to the next screen (cart page) [just like flipkart].

here is my piece of code:

    @IBAction func addToCartbtnTapped(_ sender: Any) {
        if let info = detailInfo {
            let cartData = CartStruct(cartItems: info, cartQuantity: 1)
            self.saveCart(data: cartData)
            showAlert()
            (sender as AnyObject).setTitle("Go to Cart", for: .normal)
            
            let cart = self.storyboard?.instantiateViewController(withIdentifier: "CartViewController") as? CartViewController
            self.navigationController?.pushViewController(cart!, animated: true)
        }
    }

I'm able to change the title of the button. But whenever I click on the button for nth number of time also, the product is getting added to the cart, screen is not navigating.

How to solve this issue?

Update..

    override func viewDidLoad() {
        super.viewDidLoad()
        UserDefaults.standard.string(forKey: "btn")
    }



    @IBAction func addToCartbtnTapped(_ sender: Any) {
        if !Clicked {
            if let info = detailInfo {
                let cartData = CartStruct(cartItems: info, cartQuantity: 1)
                self.saveCart(data: cartData)
                showAlert()
                addingTOCart.setTitle("Go to Cart", for: .normal)
                UserDefaults.standard.set("Go to Cart", forKey: "btn")
                print("Clicked")
                Clicked = true
                return
            }
        }
        
        if Clicked {
            print("Perform Action")
            let cart = self.storyboard?.instantiateViewController(withIdentifier: "CartViewController") as? CartViewController
            self.navigationController?.pushViewController(cart!, animated: true)
        }
    }

This is how I am trying to store the "Go to Cart" state. But not working.. please suggest!

CodePudding user response:

You can apply check on your button title for performing two different actions. Also you are showing alert and pushing View Controller at the same time which might be the reason for screen not navigating.

@IBAction func addToCartbtnTapped(_ sender: UIButton) {
        if let info = detailInfo {
            switch sender.currentTitle! {
            case "Add to Cart":
                let cartData = CartStruct(cartItems: info, cartQuantity: 1)
                self.saveCart(data: cartData)
                showAlert()
                (sender as AnyObject).setTitle("Go to Cart", for: .normal)
            case "Go to Cart":
                let cartData = CartStruct(cartItems: info, cartQuantity: 1)
                self.saveCart(data: cartData)
                showAlert()
                (sender as AnyObject).setTitle("Go to Cart", for: .normal)
            default:
                print("Default Case")
            }
        }
    }

CodePudding user response:

Add this code to check cart is already added or not, If added change title according in your detail controller:

 override func viewWillAppear(_ animated: Bool) {
            if let info = detailInfo {
                let buttonTItle = (self.checkCartData(cartInfo: info) ? "Go to Cart"  : "Add to Cart")
                addToCartButton.setTitle(buttonTItle, for: .normal)
            }
        }

Next, Check before adding to cart. If already added, will navigate to cart page else add new cart item(changing button title too).

@IBAction func addToCartbtnTapped(_ sender: Any) {
            if let info = detailInfo {
                if checkCartData(cartInfo: info) {
                    let cart = self.storyboard?.instantiateViewController(withIdentifier: "CartViewController") as? CartViewController
                    self.navigationController?.pushViewController(cart!, animated: true)
                } else {
                    let cartData = CartStruct(cartItems: info, cartQuantity: 1)
                    self.saveCart(data: cartData)
                    showAlert()
                    (sender as AnyObject).setTitle("Go to Cart", for: .normal)
                }
            }
        }

Check Cart data here:

        func checkCartData(cartInfo: jsonstruct) -> Bool {
            guard let cart = self.getCartData() else { return false }
            return (cart.contains(where: { $0.cartItems.name == cartInfo.name }) ? true : false )
        }

Get all Cart Data with this method:

        func getCartData() -> [CartStruct]? {
            let defaults = UserDefaults.standard
            var tempCart: [CartStruct]?
            if let cdata = defaults.data(forKey: "cartt") {
                tempCart = try! PropertyListDecoder().decode([CartStruct].self, from: cdata)
            }
            return tempCart
        }

CodePudding user response:

import UIKit

class ViewController: UIViewController {

   @IBOutlet weak var btn: UIButton!
   var Clicked:Bool = false
   override func viewDidLoad() {
       super.viewDidLoad()
       // Do any additional setup after loading the view.
   }

   @IBAction func btnClick(_ sender: Any) {
       if !Clicked {
           btn.setTitle("Click", for: .normal)
           print("Clicked")
           Clicked = true
           return
       }
       
       if Clicked {
           print("Perform Action")
       }
       
   }

}

  • Related