首页 文章

如何单击按钮并更改tablewviewcell中的标签文本

提问于
浏览
-1

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

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

我不知道怎么做?
sample image

2 回答

  • 0

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

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

    然后将初始数量值添加到 quantityArray For example : If your list array count 10 and initial quantity of all item will be one means 将初始值添加到数组中

    for i in 0 ..< 10 {
       quantityArray.append(1)
    }
    

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

    从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

    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
    }
    

    如果你在滚动表视图之后使用这样的话,那么单元格中的数量将从数量数组中填充

    希望对你有帮助

  • 0

    您所要做的就是为按钮添加动作并完成工作 .

    @IBAction func increase() {
        quantityLabel.text = "\(quantity)" // increase the quantity number and set it
    }
    

    顺便说一句 . 在获得任何帮助之前,您应该考虑发布您的代码 .

相关问题