如何在iOS Swift4的Tableview单元格中增加和减少变量

时间:2019-07-15 10:29:34

标签: ios swift uitableview swift4

我在tableview中有一个数据。我有两个按钮+和-,我想在单击按钮时增加和减少值。请检查下面的图片以准确了解。

enter image description here

当我按下第一个单元格的加号图标时,该值将反映在最后一个单元格中。

这是我的代码:-

const char * const ones[20] = {"zero", "one", "two", 
                               "three","four","five","six","seven",
                               "eight","nine","ten","eleven","twelve",
                               "thirteen","fourteen","fifteen","sixteen",
                               "seventeen", "eighteen","nineteen"};

}

我也尝试了此链接:-

+/- quantity of products in Cart View Controller with buttons each on a TableViewCell, which gets default quantity as integer from an array

How do I increment/decrement a label value with two buttons pressed in tableview Swift

谢谢。

2 个答案:

答案 0 :(得分:0)

@Mayur尝试执行此操作,并在 Increment (增量)和 Decrement (递减)按钮的选择器上进行更改。

func decrementbuttonClicked(sender : UIButton){
        if let cell = sender.superview?.superview as? UITableViewCell{ // use superview property till you cell not accessible here
            let counterLbl = cell.contentView.viewWithTag(2007) as! UILabel
            let intCounterValue = Int(counterLbl.text ?? "0") // fix error for conversion from strign to integer
            if(intCounterValue > 0){
                intCounterValue -= 1;
            }

            if let indexPath = tblViewCustomerInfo.indexPath(for: cell){
                let product = productArray[indexPath.row]
                product.price = intCounterValue
            }
        }
    }

func incrementbuttonClicked(sender : UIButton){
    if let cell = sender.superview?.superview as? UITableViewCell{ // use superview property till you cell not accessible here
        let counterLbl = cell.contentView.viewWithTag(2007) as! UILabel
        var intCounterValue = Int(counterLbl.text ?? "0") // fix error for conversion from strign to integer
        intCounterValue += 1;

        if let indexPath = tblViewCustomerInfo.indexPath(for: cell){
            let product = productArray[indexPath.row]
            product.price = intCounterValue
        }
    }
}

答案 1 :(得分:-1)

不是将counterValue定义为Int,而是将其设置为array [Int]并根据索引设置计数器值。

在cellforrowindexpath中-为类似按钮定义标签。 button.tag =索引

并使其发挥功能-

@objc func incrementbuttonClicked(sender: UIButton) { index = sender.tag }