我有集合视图单元格,并且在集合视图单元格中有步进器和产品名称标签。我有六个产品显示在集合视图单元格上。我想通过点击添加到购物车按钮将产品添加到购物车/订单。
点击添加到购物车按钮后,将隐藏添加到购物车按钮,并显示步进器,如下图所示。
这是我的集合视图单元格的代码:
protocol OrderCellDelegate {
func stepperValueChange(at selectedIndexPath: IndexPath, stepperValue: Int)
}
class OrderCell: UICollectionViewCell {
@IBOutlet weak var stepper: GMStepper!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet var addToCartButton: UIButton!
var productData : Product? {
didSet {
updateUI()
}
}
var indexPath: IndexPath?
var delegate: OrderCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
setStepper()
}
@IBAction func addToCartButtonDidTapped(_ sender: Any) {
stepper.value = 1.0
}
@IBAction func stepperValueChanged(_ sender: Any) {
print("stepper value: \(stepper.value)")
guard let selectedIndexPath = indexPath else {return}
let value = Int(stepper.value)
self.delegate?.stepperValueChange(at: selectedIndexPath, stepperValue: value)
}
func setStepper() {
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)
}
}
}
正如您在上面的addToCartButtonDidTapped
方法中所看到的那样,我以编程方式将步进器值设置为1,我希望上面蓝色步进器中的数字为1,但它显示的是零而不是1(例如上面的屏幕截图)
我使用@IBAction连接stepperValueChanged
方法,并将'value change'作为发送的事件。因此,当stepper.value = 1.0
内部触发addToCartButtonDidTapped
时,stepperValueChanged
方法内部的所有代码都会自动触发
但是,即使我强迫将其设为1,为什么也变为零?你能帮我这个吗?
这是Google驱动器中的文件项目:https://drive.google.com/file/d/1VBR0HkR2Wb2RF2m1CC3zI8a5hJipHW7W/view
这是我的视图控制器代码:
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 stepperValueChange(at selectedIndexPath: IndexPath, stepperValue: Int) {
guard let userOrder = order else {return}
let selectedProduct = allProducts[selectedIndexPath.item]
let maximumQuantityOfProduct = 100
let minimumQuantityOfProduct = 1
if stepperValue == minimumQuantityOfProduct - 1 {
// remove the product from the cart if the stepper value is one below the minimum allowable quantity
Order.removeProductFromOrderRealmDatabase(userOrder: userOrder, selectedProduct: selectedProduct)
Product.changeProductQuantityInRealmDatabase(selectedProduct: selectedProduct, quantity: 0)
} else if stepperValue == minimumQuantityOfProduct {
// it means add to cart button is tapped
if userOrder.products.filter("productID == %@", selectedProduct.productID).first == nil {
Order.addProductToOrderRealmDatabase(userOrder: userOrder, selectedProduct: selectedProduct)
} else {
Order.removeProductFromOrderRealmDatabase(userOrder: userOrder, selectedProduct: selectedProduct)
}
} else if stepperValue > minimumQuantityOfProduct && stepperValue <= maximumQuantityOfProduct {
Product.changeProductQuantityInRealmDatabase(selectedProduct: selectedProduct, quantity: stepperValue)
}
collectionView.reloadData()
}
}
// 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
}
}
这是产品代码:
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])
}
}
这是订单模型:
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) {
// 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
})
}
}
static func removeProductFromOrderRealmDatabase(userOrder: Order, selectedProduct: Product) {
// to check wheter the selected product from user is already in Order or not
if let matchingProduct = userOrder.products.filter("productID == %@", selectedProduct.productID).first {
RealmService.shared.save(expression: {
matchingProduct.hasBeenAddedToCart = false
guard let index = userOrder.products.index(where: {$0.productID == matchingProduct.productID}) else {return}
userOrder.products.remove(at: index)
matchingProduct.quantityInCart -= 1
})
}
}
}