You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS开发:实现购物车与心愿单数组间商品自由移动

解决方案:实现购物车与心愿单的商品互移

1. 完善表格Cell的交互逻辑

先给SneakersTableCell中的wishButton添加点击事件和回调闭包,用来通知上层控制器触发商品移动操作:

final class SneakersTableCell: UITableViewCell {
    // ... 保留原有代码 ...
    
    // 添加心愿单回调闭包
    var addToWishlist: ((BagProduct) -> ())?
    // 保存当前cell对应的商品
    private var currentProduct: BagProduct?

    override init(style: UITableViewCell.CellStyle,reuseIdentifier: String?) {
        super.init(style: .default,reuseIdentifier: "SneakersTableCell")
        print("New cell has been create")
        setupUI()
        setupConstraints()
        removeButton.addTarget(self, action: #selector(removeButtonTapped(_:)), for: .touchUpInside)
        // 给wishButton绑定点击事件
        wishButton.addTarget(self, action: #selector(wishButtonTapped(_:)), for: .touchUpInside)
    }
    
    // ... 保留原有代码 ...
    
    @objc func wishButtonTapped(_ sender: UIButton) {
        print("Tapped wish button")
        guard let product = currentProduct else { return }
        addToWishlist?(product)
    }
    
    // 修改configure方法,保存当前商品
    func configure(product: BagProduct) {
        currentProduct = product
        productImageView.image = product.image
        categoryLabel.text = product.category
        nameLabel.text = product.name
        priceLabel.text = "\(product.price)€"
        sizeLabel.text = "Size: \(product.size)"
        colorLabel.text = "Color: \(product.color)"
    }
}

2. 在单例类中添加商品移动方法

修改Sneakers单例,实现购物车与心愿单之间的商品转换、移动逻辑:

class Sneakers {
    static let shared = Sneakers()
    var bagProducts = [
        BagProducts(image: UIImage(named: "Image")!, category: "Men", name: "Adidas Gazelle", price: 100.00, size: 40, color: "Blue"),
        BagProducts(image: UIImage(named: "Image")!, category: "Men", name: "Adidas Gazelle", price: 100.00, size: 40, color: "Blue"),
    ]
    
    var wishProducts = [
        WishProducts(image: UIImage(named: "AdidasGalaxy")!, category: "Women", name: "Adidas Galaxy 6", price: 55.00),
        WishProducts(image: UIImage(named: "NewBalance")!, category: "Men", name: "New Balance BB550", price: 150.00),
    ]
    
    // 购物车商品移至心愿单
    func moveBagProductToWishlist(_ product: BagProduct) {
        // 将BagProduct转换为WishProduct
        let wishProduct = WishProducts(
            image: product.image,
            category: product.category,
            name: product.name,
            price: product.price
        )
        wishProducts.append(wishProduct)
        // 从购物车移除原商品(匹配所有字段避免误删重复项)
        if let index = bagProducts.firstIndex(where: {
            $0.image == product.image &&
            $0.category == product.category &&
            $0.name == product.name &&
            $0.price == product.price &&
            $0.size == product.size &&
            $0.color == product.color
        }) {
            bagProducts.remove(at: index)
        }
    }
    
    // 心愿单商品移至购物车(需补充size和color,示例用默认值,实际可弹窗让用户选择)
    func moveWishProductToBag(_ product: WishProduct, size: Int, color: String) {
        let bagProduct = BagProducts(
            image: product.image,
            category: product.category,
            name: product.name,
            price: product.price,
            size: size,
            color: color
        )
        bagProducts.append(bagProduct)
        // 从心愿单移除原商品
        if let index = wishProducts.firstIndex(where: {
            $0.image == product.image &&
            $0.category == product.category &&
            $0.name == product.name &&
            $0.price == product.price
        }) {
            wishProducts.remove(at: index)
        }
    }
}

3. 在ViewController中处理回调并刷新UI

以购物车页面BagViewController为例,配置Cell时绑定闭包,处理商品移动并刷新表格:

class BagViewController: UIViewController, UITableViewDataSource {
    let tableView = UITableView()
    let sneakers = Sneakers.shared
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 配置tableView基础设置
        tableView.frame = view.bounds
        tableView.register(SneakersTableCell.self, forCellReuseIdentifier: "SneakersTableCell")
        tableView.dataSource = self
        view.addSubview(tableView)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sneakers.bagProducts.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SneakersTableCell", for: indexPath) as! SneakersTableCell
        let product = sneakers.bagProducts[indexPath.row]
        cell.configure(product: product)
        
        // 绑定移至心愿单的回调
        cell.addToWishlist = { [weak self] product in
            self?.sneakers.moveBagProductToWishlist(product)
            self?.tableView.reloadData()
            // 若需同步刷新心愿单页面,可通过通知或跨页面回调实现
        }
        
        // 绑定移除商品的回调
        cell.removeMe = { [weak self] cell in
            guard let indexPath = self?.tableView.indexPath(for: cell) else { return }
            self?.sneakers.bagProducts.remove(at: indexPath.row)
            self?.tableView.deleteRows(at: [indexPath], with: .fade)
        }
        return cell
    }
}

关键说明

  • 结构体转换:由于BagProducts和WishProducts是不同结构体,移动时需手动映射字段,确保数据完整传递。
  • 商品匹配:移除商品时通过全字段匹配避免误删,若商品有唯一ID,用ID匹配会更高效可靠。
  • 反向移动:如需实现心愿单到购物车的移动,给心愿单Cell添加类似回调,调用moveWishProductToBag方法时补充size和color字段即可。

内容的提问来源于stack exchange,提问作者Fábio Galante

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 13:37:03