Swift:- 在自定义 tableview 单元格中单击按钮时将标签值增加 1

Swift:- Increment label value by 1 on button click in custom tableview cell

我正在尝试在自定义 table 单元格内单击按钮时将标签值增加 1。我可以在不同的单元格中以不同的方式更改值,但问题是如果我在第一个单元格标签中点击 + 从 0 变为 1,当我在第二个单元格标签中点击 + 时直接从 0 变为 2,在其他单元格中依此类推。我该如何解决这个问题?

     var counts = 0

    @IBAction func addPressed(_ sender: UIButton) {
    let indexPath = IndexPath(row: sender.tag, section: 0)
    let cell = tblview.cellForRow(at: indexPath) as! HomeDetailsTableViewCell
    counts = (counts + 1)
    cell.lblNoOfItems.text = "\(counts)"
}

有两种方法可以实现:

1.Array 中每个单元格的计数保持在 controller 级别,每次按 button,从数组中获取计数并使用它,即

var counts = [Int](repeating: 0, count: 10) //10 is the number of cells here

@IBAction func addPressed(_ sender: UIButton) {
    let indexPath = IndexPath(row: sender.tag, section: 0)
    let cell = tblview.cellForRow(at: indexPath) as! HomeDetailsTableViewCell
    counts[indexPath.row] += 1
    cell.lblNoOfItems.text = "\(counts[indexPath.row])"
}

2. 将每个单元格的计数保留在自定义单元格本身中,即在 HomeDetailsTableViewCell 中,即

class HomeDetailsTableViewCell: UITableViewCell {
    var count = 0
    //Rest of the code...
}

@IBAction func addPressed(_ sender: UIButton) {
        let indexPath = IndexPath(row: sender.tag, section: 0)
        let cell = tblview.cellForRow(at: indexPath) as! HomeDetailsTableViewCell
        cell.count += 1
        cell.lblNoOfItems.text = "\(cell.count)"
}

此外,您实现添加 + button 代码的方式不正确。您必须在 HomeDetailsTableViewCell 本身内实现它,即

class HomeDetailsTableViewCell: UITableViewCell {
    @IBOutlet weak var lblNoOfItems: UILabel!
    var count = 0

    @IBAction func addPressed(_ sender: UIButton) {
        self.count += 1
        self.lblNoOfItems.text = "\(self.count)"
    }
    //Rest of the code...
}

这是因为您对 class 中的所有单元格都使用了一个全局变量,如果您想为每个单元格保持不同的计数,则必须为每个单元格使用不同的变量手机,我只是给你指路所以找到你的路 .

为您的计数创建一个数据源,并使用您用于 table 的相同数据源对其进行初始化,假设您有一个字符串数组用于 table 查看数据源,让我们创建列出包含您的标题的数组并用它来计数。我为您提供了解决方案中的所有步骤,您只需将代码放在正确的位置即可:-

//Suppose this is your tableivew data source
let list : [String] = ["Title1","Title2","Title3"]

//Make a dictionary that is going to be your datasource of tableview holding the count too
var listDict : [[String:Any]] = []
for item in list{
    let dict : [String:Any] = ["title":item,"count":Int(0)]
    listDict.append(dict)
}

//Where you are performing the actions like in didSelectRow or in any button
let cellIndexPath : IndexPath = IndexPath(item: 0, section: 0) // Get the indexPath of Cell

//Update the count
if let count = listDict[cellIndexPath.row]["count"] as? Int{
    let newValue = count + 1
    listDict[cellIndexPath.row]["count"] = newValue
}

//Reload the tableview cell of update manually your choice I'm reloading the cell for short
let tableview = UITableView()
tableview.reloadRows(at: [cellIndexPath], with: .fade)

您可以在 Swift 5

中使用以下代码获得此问题的答案

//第一步

在您的 TableViewCell 中

import UIKit

@objc protocol CellDelagate : NSObjectProtocol {

    func addPressed(_ cell: TableViewCell)
}

class TableViewCell: UITableViewCell {

    var cellDelagate: CellDelagate?
    var indexPath : IndexPath?
    @IBOutlet weak var gPaybutton: UIButton!
    @IBOutlet weak var proceesingLabel: UILabel!

    var count = 0

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    @IBAction func proccessingButtonTapped(_ sender: UIButton) {

        self.cellDelagate!.addPressed(self)
        if gPaybutton.tag == indexPath?.row {

        }
    }
}

// 第二步

在你的ViewController

里面
class ViewController: UIViewController {

    @IBOutlet weak var tableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
}

extension ViewController: UITableViewDataSource, UITableViewDelegate, CellDelagate {

    func addPressed(_ cell: TableViewCell) {

        cell.count += 1
        cell.proceesingLabel.text = "Processing : \(cell.count)"
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return yourArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell")! as? TableViewCell//1.

        cell?.indexLabel?.text = yourArray[indexPath.row] //2.
        cell?.cellDelagate = self //3.
        cell?.tag = indexPath.row //4.
        return cell! //5.
    }
}