Swift:在自定义tableview单元格中,通过按钮点击将标签值增加1

3

我正在尝试在自定义表格单元格中的按钮点击时将标签值增加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
这是因为每次你都在使用全局的 count 变量来设置每个 UITableViewCelllabel 中的值。因此,每次点击时使用的是更新后的 count 值。 - PGDev
@PGDev 我该如何修复它? - Harsh
3个回答

3

有两种方法可以实现这个目标:

1.控制器级别上保持每个单元格的计数在一个数组中,每次按下按钮时,从数组中获取计数并使用它,即:

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)"
}

此外,您实现添加+ 按钮代码的方法是不正确的。您必须在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...
}

尝试使用答案中的最后一个建议来实现代码。 - PGDev
当然。请接受答案,这样它也可以帮助其他人。 - PGDev
完美无瑕 :) 没有比这更好的答案了,是的,我用了最后一个。 - Harsh
最后的解决方案确实更好!干杯!! - tryKuldeepTanwar

1

您可以使用以下代码在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.
    }
}

我已经测试了你的代码,但是那一行 "self.cellDelagate!.addPressed(self)" 抛出了以下错误:"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"。我有什么遗漏吗? - Ing. Ron
@Ing.Ron 很抱歉回复晚了。你解决了这个问题吗?如果没有,请告诉我。 - Sreekanth G
@Ing.Ron 如果您还记得问题是什么,请在此处记录该问题。这可能有助于其他人。 - Sreekanth G

0

这是因为你正在使用一个全局变量来处理类中的所有单元格,如果你想为每个单元格分别维护计数,你必须为每个单元格使用不同的变量,我只是给你方向,让你自己找出解决方法。

为计数创建一个数据源,并使用与表格相同的数据源进行初始化,例如,假设你有一个用于tableview数据源的字符串数组,请创建一个列表数组,其中包含标题和计数。 我在我的解决方案中给出了所有步骤,你只需要将代码放在正确的位置:-

//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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接