我有一个表格 View ,其中每个单元格包含两个按钮 + 和 - 以及一个在按钮值更改时更新值的标签
但是当我点击标签集 1 中的第一行添加按钮但是当我点击第二行时点击添加按钮然后标签值集 2 而不是 1
这是代码
func btnAddAction(sender : UIButton)
{
let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: sender.tag)) as! DetailTableViewCell
k++
cell.lblCount.text = "\(k)"
if k * item_priceArr[sender.tag] >= 1000
{
lblCartCount.frame = CGRectMake(289, lblCartCount.frame.origin.y, 28, 15);
}
else if k * item_priceArr[sender.tag] >= 100 && j != 2
{
lblCartCount.frame = CGRectMake(291, lblCartCount.frame.origin.y, 22, 15);
j = 2
}
else if k * item_priceArr[sender.tag] <= 99 && j != 1
{
lblCartCount.frame = CGRectMake(293, lblCartCount.frame.origin.y, 15, 15);
j = 1
}
print("\(cou! + (k * item_priceArr[sender.tag]))")
lblCartCount.text = "\(cou! + (k * item_priceArr[sender.tag]))"
}
func btnMinusAction(sender : UIButton)
{
let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: sender.tag)) as! DetailTableViewCell
k--
if k * item_priceArr[sender.tag] >= 1000
{
lblCartCount.frame = CGRectMake(289, lblCartCount.frame.origin.y, 28, 15);
}
else if k * item_priceArr[sender.tag] >= 100 && j != 2
{
lblCartCount.frame = CGRectMake(291, lblCartCount.frame.origin.y, 22, 15);
j = 2
}
else if k * item_priceArr[sender.tag] <= 99 && j != 1
{
lblCartCount.frame = CGRectMake(293, lblCartCount.frame.origin.y, 15, 15);
j = 1
}
if k >= 0
{
cell.lblCount.text = "\(k)"
lblCartCount.text = "\(cou! + (k * item_priceArr[sender.tag]))"
defaults.setInteger(Int(lblCartCount.text!)!, forKey: appDelegate.device_id)
defaults.setInteger(k, forKey: "Device_Key")
}
else
{
k = 0
JLToast.makeText("0").show()
}
}
最佳答案
似乎变量 k
的作用域遍及整个 viewController。因此,当 k 在任何单元格中更新时,它的值对于 k 显示的所有单元格都会发生变化。每个单独的单元格都需要一个 k
变量。这可以通过在自定义单元格类中声明 var k = 0
DetailTableViewCell.swift
class DetailTableViewCell : UITableViewCell {
var k = 0 //Add this variable to the individual cell.
}
TableViewController.swift
func btnAddAction(sender : UIButton)
{
let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: sender.tag)) as! DetailTableViewCell
cell.k++ //Now use cell.k to get increment/decrement for each individual cell.
}
关于swift - UITableview 单元格值不会 swift 改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35179479/