如何单击按钮并更改 tablewviewcell 中的标签文本 [英] How can i click button and change label text in tablewviewcell

查看:24
本文介绍了如何单击按钮并更改 tablewviewcell 中的标签文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在每个 TableViewCell 中单击按钮时更改标签文本

I want to change label text when i was click button in every TableViewCell

我的意思是有 2(-,+) 个按钮和 1 个标签,当我点击按钮时,标签会增加或减少.

I mean have 2(-,+) button and 1 label, When I click on the button, the label will increase or decrease.

我不知道怎么做?

推荐答案

你需要维护一个quantityArray来存储每个索引的当前数量

you need to maintain a quantityArray to store current quantity of every index

var quantityArray:[Int] = [] //initialize quantity array

然后将初始数量值添加到 quantityArray例如:如果您的列表数组数为 10,并且所有项目的初始数量将是一种方法向数组添加初始值

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

然后在你的 tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)

从quantityArray分配数量值

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)

将以下函数添加到您的 viewcontroller

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
}

如果你这样使用,即使在滚动 tableview 之后,单元格中的数量也会从数量数组中填充

If you use like this even after scroll tableview also quantity in the cell will be populated from quantity array

希望对你有帮助

这篇关于如何单击按钮并更改 tablewviewcell 中的标签文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆