问题
I want to change label text when i was click button in every TableViewCell
I mean have 2(-,+) button and 1 label, When I click on the button, the label will increase or decrease.
I have no idea How to do it?

回答1:
you need to maintain a quantityArray
to store current quantity of every index
var quantityArray:[Int] = [] //initialize quantity array
then add initial quantity values to quantityArray
For example : If your list array count 10 and initial quantity of all item will be one means
add initial values to the array
for i in 0 ..< 10 {
quantityArray.append(1)
}
then in your tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
assign quantity value from quantityArray
cell.qtyLbl.text = "\(quantityArray[indexPath.row])"
cell.incrementBtn.tag = indexPath.row
cell.incrementBtn.addTarget(self, action: #selector(self.incrementBtnClicked(_:)), for: .touchUpInside)
cell.decrementBtn.tag = indexPath.row
cell.decrementBtn.addTarget(self, action: #selector(self.decrementBtnClicked(_:)), for: .touchUpInside)
add below functions into your viewcontroller
func incrementBtnClicked(_ sender:UIButton){
let increasedQty = quantityArray[sender.tag]+1
self.quantityArray.replaceSubrange(sender.tag, with: increasedQty)
self.tableView.reloadData
}
func decrementBtnClicked(_ sender:UIButton){
let decreasedQty = quantityArray[sender.tag]-1
self.quantityArray.replaceSubrange(sender.tag, with: decreasedQty)
self.tableView.reloadData
}
If you use like this even after scroll tableview also quantity in the cell will be populated from quantity array
Hope this will help you
回答2:
All you have to do is to add an action to your button and do your job.
@IBAction func increase() {
quantityLabel.text = "\(quantity)" // increase the quantity number and set it
}
btw. before getting any help you should consider posting your code.
来源:https://stackoverflow.com/questions/47527937/how-can-i-click-button-and-change-label-text-in-tablewviewcell