单击按钮时增加和减少值 [英] Increase and Decrease values on Button click

查看:30
本文介绍了单击按钮时增加和减少值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 UIlabel 上显示价值.当我按 UIbutton 增加或减少标签上的值时.这是我的代码,当我运行我的项目时,我的 uilabel 没有任何价值.

I want to show value on UIlabel. when I press UIbutton to increase or decrease values on label. This is my code and when I am running my project but I didn't get any value on my uilabel.

@IBAction func btnIncreaseAction(_ sender: Any) {


    var count = 0
    count = (count + 1)

   if let cell = (sender as? UIButton)?.superview?.superview?.superview as? ShoppingCell
    {
        //cell.lblForOnty.text = "\(cell.lblForOnty.text ?? 0 + 1)"
        cell.lblForOnty.text = String(count)
    }



}



  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! ShoppingCell

    var someValue: Int = 0 {
        didSet {
            cell.lblForOnty.text = "\(count)"
        }
    }

    return cell
}
}

推荐答案

这是应该在您的 ViewController 中的代码.我假设 numberOfSections 是 1 并且在 numberOfRowsInSection 中,你正在传递你想要的行数.否则你需要修改这一行:let indexPath = IndexPath(row: sender.tag, section: 0).

This is the code which should be in your ViewController. I am assuming that numberOfSections is 1 and in numberOfRowsInSection you are passing then number of rows you want. Else you need to modify this line : let indexPath = IndexPath(row: sender.tag, section: 0).

var count = 0 // Count variable should be a global variable, you need it to decrease the value too.
@objc func increaseCounter(sender: UIButton) {
    //increase logic here
    count = (count + 1)
    let indexPath = IndexPath(row: sender.tag, section: 0)
    let cell = tableView.cellForRow(at: indexPath)
    cell.lblForOnty.text = "\(count)"
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! ShoppingCell

    // Add tag and action to your button
    cell.yourButton.tag = indexPath.row
    cell.yourButton.addTarget(self, action: #selector(increaseCounter(sender:)), for: .touchUpInside)

    return cell
}

这篇关于单击按钮时增加和减少值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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