uitableviewcells之间的通信

Communication between uitableviewcells

我有两个 UITableViewCells。当触发第一个 tableview 单元格中的按钮操作时,我试图在第二个 uitableviewcell 中创建一个 UI 。我尝试了代表但没有用。

protocol ProductColorTableViewCellDelegate {
    func changeUnit(selectedColor: String, _ modelArray : [UnitAndColors])
}

class ProductColorTableViewCell: UITableViewCell { 
var delegate: ProductColorTableViewCellDelegate?

 @objc private func selectColor(_ sender : UIButton) {
    let tag : Int = sender.tag
    guard let model : UnitAndColors = self.arrayUnitsAndColor?[tag] else { return }
    delegate?.changeUnit(selectedColor: model.colorDesc ?? "", arrayUnitsAndColor ?? [])
}
}

第二个tableviewcell

class PackagingTableViewCell: UITableViewCell { 

let productColorTableViewCell = ProductColorTableViewCell()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    productColorTableViewCell.delegate = self
    
}
}

extension PackagingTableViewCell: ProductColorTableViewCellDelegate {
    func changeUnit(selectedColor: String, _ modelArray: [UnitAndColors]) {
        selectedColorName = selectedColor
        self.unitStackView.removeAllArrangedSubviews()
        self.arrayUnitsAndColor?.removeAll()
        self.arrayUnitsAndColor = modelArray
        let filteredArray = self.arrayUnitsAndColor?.unique { [=11=].colorDesc == selectedColorName }
        var i : Int = 0
        filteredArray?.forEach { units in
            let vw = self.createUnits(units, tag: i)
            self.unitStackView.addArrangedSubview(vw)
            vw.snp.makeConstraints {
                [=11=].size.equalTo(40.0)
            }
            i = i + 1
        }
    }
}
class ProductColorTableViewCell: UITableViewCell { 
var delegate: ProductColorTableViewCellDelegate?
 @IBOutlet weak var selectColorButtonOL: UIButton!
 @IBAction func selectColor(_ sender : UIButton) {
    let tag : Int = sender.tag
    guard let model : UnitAndColors = self.arrayUnitsAndColor?[tag] else { return }
    delegate?.changeUnit(selectedColor: model.colorDesc ?? "", arrayUnitsAndColor ?? [])
}
}
extension ViewController: UItableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ProductColorTableViewCell") as! ProductColorTableViewCell
      cell.delegate = self
      cell.selectColorButtonOL.tag = indexPath.row
        return cell
    }
}
extension ViewController: ProductColorTableViewCellDelegate{
func changeUnit(selectedColor: String, _ modelArray: [UnitAndColors]) {
        // implement what you want
    }
}

您可以通过将 indexPath.row + 1 传递给 tableView.cellForRowAt() 来获取下一个单元格,然后调用执行所需任务的函数。