访问Swift中单元格中的标签

问题描述 投票:0回答:3

我在表视图中创建了一个自定义单元格。单元格中有一些按钮和标签。我正在创建一个委托方法,并在按钮的操作上调用它。按钮也在单元格中。现在我正在尝试每当用户按下按钮时标签文本应该增加1。我正在尝试访问cellForRow委托方法之外的单元格标签但是失败了。如何在我的按钮操作中的cellForRow委托方法之外的单元格中获取标签?我试过一些代码,这是在我的手机类中,

protocol cartDelegate {
func addTapped()
func minusTapped()
}

var delegate : cartDelegate?
 @IBAction func addBtnTapped(_ sender: Any) {

    delegate?.addTapped()
}

@IBAction func minusBtnTapped(_ sender: Any) {

    delegate?.minusTapped()
}

这是在我的视图控制器类中,

extension CartViewController : cartDelegate{

func addTapped() {

    total += 1
    print(total)

}

func minusTapped() {
    total -= 1
    print(total)
}

这是cellForRow方法,

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

{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CartTableViewCell

    cell.dishTitleLbl.text = nameArray[indexPath.row]
    cell.priceLbl.text = priceArray[indexPath.row]
    price = Int(cell.priceLbl.text!)!
    print(price)
    cell.dishDetailLbl.text = "MANGO,Apple,Orange"
    print(cell.dishDetailLbl.text)
    total = Int(cell.totalLbl.text!)!

    cell.selectionStyle = .none
    cell.backgroundColor = UIColor.clear
    cell.delegate = self
    return cell
}

我想在addTapped和minusTapped函数中访问priceLbl。

ios swift uitableview
3个回答
1
投票

更改协议以传递单元格:

protocol cartDelegate {
func addTappedInCell(_ cell: CartTableViewCell)
func minusTappedInCell(_ cell: CartTableViewCell)
}

更改您的IBActions以通过单元格:

@IBAction func addBtnTapped(_ sender: Any) {
    delegate?.addTappedInCell(self)
}

@IBAction func minusBtnTapped(_ sender: Any) {
    delegate?.minusTappedInCell(self)
}

然后你的代表可以为小组做任何想做的事情。


0
投票

它应该是一个简单的东西:self.priceLbl.text = "count = \(total)"


0
投票

为了能够访问label内部的CartViewController,但在cellForRowAt之外,您必须能够访问特定的单元格。要实现这一点,因为你动态地将可重复使用的细胞出列,你将需要一个该单元格的indexPath然后你可以让tableView给你一个单元格:

// I will here assume it is a third cell in first section of the tableView
let indexPath = IndexPath(row: 2, section: 0)
// ask the tableView to give me that cell
let cell = tableView.cellForRow(at: indexPath) as! CartTableViewCell
// and finally access the `priceLbl`
cell.priceLbl.text = priceArray[indexPath.row]
© www.soinside.com 2019 - 2024. All rights reserved.