这个问题在这里已有答案:
我的VC中有一个表格视图。在单元格内部有一些标签和按钮。我在标签中传递了值,现在我正在尝试当我按下同样在该单元格中的按钮时它应该增加标签的值。该标签中的值来自之前的VC。当按下按钮时,我已经为它做了一个代表,当按下按钮时,它应该按照其中的第一个价格增加标签的值。我正在尝试获得该单元索引路径,但不打算进行竞争。我的代码是这样的,在我的cel类我有这个协议,
protocol cartDelegate {
func addTappedInCell(_ cell: CartTableViewCell)
func minusTappedInCell(_ cell: CartTableViewCell)
}
var delegate : cartDelegate?
@IBAction func addBtnTapped(_ sender: Any) {
delegate?.addTappedInCell(self)
}
@IBAction func minusBtnTapped(_ sender: Any) {
delegate?.minusTappedInCell(self)
}
在我看来控制器我正在尝试这个,
extension CartViewController : cartDelegate{
func addTappedInCell(_ cell: CartTableViewCell) {
guard let indexPath = cartTableView?.indexPath(for: cell) else { return }
print(indexPath)
total += 1
cell.totalLbl.text = String(total)
print(cell.priceLbl.text!)
count = "5"
let tPrice = cell.priceLbl.text! + count
print(tPrice)
cell.priceLbl.text = String(tPrice)
subTotalLbl.text = cell.priceLbl.text
}
func minusTappedInCell(_ cell: CartTableViewCell) {
total -= 1
cell.totalLbl.text = String(total)
price = Int(cell.priceLbl.text!)! - Int(count)!
cell.priceLbl.text = String(price)
subTotalLbl.text = cell.priceLbl.text
}
在自定义单元格类中声明一个var
var cellIndex:NSIndexPath?
并在cellForRow中设置它
cell.cellIndex = indexPath
然后在任何地方访问它
或直接使用
var index = tableView.indexPath(for:cell)