为什么在更新集合视图单元内的步进器时,我的协议委托模式的方法会自动触发?

时间:2019-01-10 14:53:54

标签: ios swift uicollectionview realm uicollectionviewcell

我正在尝试制作一个可以使用收藏视图将产品保存到购物车(订单)的应用,每个收藏视图单元格中都有一个步进器。

这是Google驱动器中的项目文件:https://drive.google.com/file/d/1Ax7VLpI8Vb2jFSJxn_Ss_TjEECbDt-fs/view?usp=sharing

,这是应用程序的屏幕截图(请忽略难看的UI): enter image description here

在集合视图单元格中显示6个产品。每个集合视图单元格都有名称标签,添加到购物车按钮和一个步进器。

添加到购物车按钮,并且步进器具有相同的尺寸,并且位于相同的位置,一旦点击添加到购物车按钮,它将隐藏“添加到购物车”按钮,并且它将像gif中一样显示步进器。这里: http://g.recordit.co/DAKMvFwQs4.gif

我将以下代码用于“收藏”视图单元格,使用协议和委托模式传递数据:

protocol OrderCellDelegate {
    func addToCartButtonDidTapped(at selectedIndexPath: IndexPath)
    func stepperDidTapped(at selectedIndexPath:IndexPath, counterValue: Int)
}


class OrderCell: UICollectionViewCell {

    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var stepper: GMStepper!
    @IBOutlet var addToCartButton: UIButton!


    var productData : Product? {
        didSet {
            setStepper()
            updateUI()
        }
    }

    var indexPath: IndexPath?
    var delegate: OrderCellDelegate?

    @IBAction func AddToCartButtonDidTapped(_ sender: Any) {
        guard let selectedIndexPath = indexPath else {return}
        self.delegate?.addToCartButtonDidTapped(at: selectedIndexPath)
    }


    @IBAction func stepperButtonDidTapped(_ sender: Any) {
        guard let selectedIndexPath = indexPath else {return}
        let value = Int(stepper.value)
        self.delegate?.stepperDidTapped(at: selectedIndexPath, counterValue: value)
    }

    func setStepper() {
        guard let product = productData else {return}
        stepper.value = Double(product.quantityInCart)
        stepper.autorepeat = false
        stepper.minimumValue = 0
        stepper.maximumValue = 100
        stepper.stepValue = 1.0

    }

    func updateUI() {
        guard let product = productData else {return}
        nameLabel.text = product.name
        setCartAndStepperButton()
    }

    private func setCartAndStepperButton() {

        guard let selectedProduct = productData else {return}

        func showStepperButton(status: Bool) {
            // to decide whether to show stepper or add to cart button.
            stepper.isHidden = !status
            stepper.isEnabled = status

            addToCartButton.isHidden = status
            addToCartButton.isEnabled = !status

        }

        if selectedProduct.quantityInCart == 0 {
            showStepperButton(status: false)
        } else {
            showStepperButton(status: true)
            stepper.value = Double(selectedProduct.quantityInCart)
        }


    }


}

这是我的视图控制器的代码:

class ViewController: UIViewController, OrderCellDelegate  {


    @IBOutlet weak var collectionView: UICollectionView!

    var order : Order!
    var allProducts = [Product]()

    override func viewDidLoad() {
        super.viewDidLoad()

        order = Order.getOrderFromRealmDatabase()
        allProducts = Product.fetchProductData()

    }


    func addToCartButtonDidTapped(at selectedIndexPath: IndexPath) {
        print("A")
        let selectedProduct = allProducts[selectedIndexPath.item]
        Order.addProductToOrderRealmDatabase(userOrder: order, selectedProduct: selectedProduct)
        collectionView.reloadData()

    }

    func stepperDidTapped(at selectedIndexPath: IndexPath, counterValue: Int) {

        print("B")


    }


}


// DATA SOURCE
extension ViewController : UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return allProducts.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "orderCell", for: indexPath) as! OrderCell

        cell.productData = allProducts[indexPath.item]
        cell.delegate = self
        cell.indexPath = indexPath

        return cell
    }

}

问题是.....

当我点击添加到购物车按钮时,它将触发我的视图控制器上的addToCartButtonDidTapped。但是...我不明白为什么当我点击添加到购物车按钮时,它还会触发stepperDidTapped方法

因此,当addToCartButtonDidTapped时,它将自动触发stepperDidTapped方法。 print(“ A”)和print(“ B”)同时触发。

您可以看到stepperDidTapped方法仅应在我点击步进器而不是“添加到购物车”按钮时触发,我在OrderCellDelegate上使用了2种不同的方法

我不明白为什么。我是否有错误的方式在收藏视图单元格内实现步进器?老实说,我不确定我的代码是否可以在上面的集合视图中实现stepper。

这是项目的文件:https://drive.google.com/file/d/1Ax7VLpI8Vb2jFSJxn_Ss_TjEECbDt-fs/view?usp=sharing

这是产品型号:

import RealmSwift


class Product : Object {

    @objc dynamic var productID : Int = 0
    @objc dynamic var name : String = ""
    @objc dynamic var unitPrice: Double = 0.0
    @objc dynamic var quantityInCart : Int = 0
    @objc dynamic var descriptionProduct : String = ""
    @objc dynamic var hasBeenAddedToCart : Bool = false


    override static func primaryKey() -> String? {
        return "productID"
    }

    convenience init(productID: Int, name: String, unitPrice: Double, descriptionProduct: String) {
        self.init()


        self.productID = productID
        self.name = name
        self.unitPrice = unitPrice
        self.descriptionProduct = descriptionProduct

    }

    static func fetchProductData() -> [Product] {

        let product1 = Product(productID: 1, name: "Product1", unitPrice: 1000, descriptionProduct: "Description of Product 1")
        let product2 = Product(productID: 2, name: "Product2", unitPrice: 2000, descriptionProduct: "Description of Product 2")
        let product3 = Product(productID: 3, name: "Product3", unitPrice: 3000, descriptionProduct: "Description of Product 3")
        let product4 = Product(productID: 4, name: "Product4", unitPrice: 4000, descriptionProduct: "Description of Product 4")
        let product5 = Product(productID: 5, name: "Product5", unitPrice: 5000, descriptionProduct: "Description of Product 5")
        let product6 = Product(productID: 6, name: "Product6", unitPrice: 6000, descriptionProduct: "Description of Product 6")

        return [product1,product2,product3,product4,product5,product6]
    }


    static func changeProductQuantityInRealmDatabase(selectedProduct: Product, quantity: Int) {

        guard let selectedProductInRealmDatabase = RealmService.shared.realm.objects(Product.self).filter("productID == %@", selectedProduct.productID).first else {return}

        RealmService.shared.updateOnCertainKey(object: selectedProductInRealmDatabase, for: ["quantityInCart": quantity])

    }



}

这是订单模型:

import RealmSwift


class Order : Object {
    @objc dynamic var userID: String = ""
    var products = List<Product>()


    convenience init (userID: String, products: List<Product>) {
        self.init()
        self.userID = "1"
        self.products = products
    }

    //MARK: - Realm Related

    static func getOrderFromRealmDatabase() -> Order {

        let userID = "1"
        let realmService = RealmService.shared.realm
        let allOrder = realmService.objects(Order.self)
        let theOrder = allOrder.filter("userID CONTAINS[cd] %@", userID).first

        if let userOrder = theOrder {
            return userOrder
        } else {
            // Order never setted up before in Realm database container
            // then create Order in realm database

            let newOrder = Order()
            newOrder.userID = userID
            newOrder.products = List<Product>()
            RealmService.shared.save(object: newOrder)
            return newOrder

        }

    }

    static func addProductToOrderRealmDatabase(userOrder: Order, selectedProduct: Product) {

        // to check wheter the selected product from user is already in Order or not

        if userOrder.products.filter("productID == %@", selectedProduct.productID).first == nil {

            // check if the selected product has already available in Product.self database or not
            if let matchingProduct = RealmService.shared.realm.objects(Product.self).filter("productID == %@", selectedProduct.productID).first {

                RealmService.shared.save(expression: {
                    userOrder.products.append(matchingProduct)
                    matchingProduct.hasBeenAddedToCart = true
                    matchingProduct.quantityInCart = 1
                })


            } else {

                RealmService.shared.save(expression: {
                    userOrder.products.append(selectedProduct)
                    selectedProduct.hasBeenAddedToCart = true
                    selectedProduct.quantityInCart = 1
                })

            }

        }

    }




}

0 个答案:

没有答案