我在表视图中制作了一个自定义单元格。单元格中有一些按钮和标签。我正在制作委托方法,并将其称为按钮的操作。该按钮也位于单元格中。现在,每当用户按按钮按钮时,标签文本应增加一个。我正在尝试访问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
}
我想访问我的附加功能和杂项功能中的pricelbl。
更改您的协议以通过单元格:
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)
}
,然后您的代表可以对单元进行任何想法。
能够访问CartViewController
内部的label
,但是在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]
应该像以下内容一样简单。 self.priceLbl.text = "count = (total)"