简体   繁体   English

增加/减少一个值并在TableViewCell Swift Xcode中的Label中显示结果

[英]Increase/Decrease a value and display results in a Label inside a TableViewCell Swift Xcode

I have a ViewController with a TableView and a TableViewCell containing multiple sections and rows. 我有一个带有TableView的ViewController和一个包含多个部分和行的TableViewCell。 I have 2 button "plus" and "minus" and a label "totalLabel" in each row. 我有2个按钮“加”和“减号”,每行有一个标签“totalLabel”。

How can I get the value displayed in the label for each specific row when the user presses the + or - button? 当用户按下+-按钮时,如何获取每个特定行的标签中显示的值?

for now when I run the app and press the + or - buttons only the totalLabel of the section 0/row 0 is working while random values just appear and disappear in the other sections/rows 现在,当我运行应用程序并按+或 - 按钮时,只有0或第0行的totalLabel工作,而随机值只是出现并在其他部分/行中消失

my tableViewCell code : 我的tableViewCell代码:

import UIKit

protocol CommandeCellDelegate: class {
}

class CommandeCell: UITableViewCell {

weak var delegate : CommandeCellDelegate!

@IBOutlet weak var drinksLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!

@IBOutlet weak var totalLabel: UILabel!

@IBOutlet weak var plusButton: UIButton!
@IBOutlet weak var minusButton: UIButton!

override func awakeFromNib() {
    super.awakeFromNib()
}


override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
}

}

here is my code for cellForRowAt : 这是我的cellForRowAt代码:

class MenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CommandeCellDelegate {

var count : Int = 0

var countValue : String!

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

    cell.plusButton.tag = indexPath.section
    cell.plusButton.tag = indexPath.row
    cell.plusButton.addTarget(self, action: #selector(self.increaseValue), for: .touchUpInside)

    cell.minusButton.tag = indexPath.section
    cell.minusButton.tag = indexPath.row
    cell.minusButton.addTarget(self, action: #selector(self.decreaseValue), for: .touchUpInside)

    if indexPath.section == 0 {
        let softInfo = softs[indexPath.row]
        cell.drinksLabel?.text = softInfo.drinkName
        cell.totalLabel?.text = // how to display countValue here?

        let HappyHourStatus = partner!.barHHStatus
        if case "0" = HappyHourStatus {
            cell.priceLabel?.text = softInfo.drinkHHPrice
        } else
            if case "1" = HappyHourStatus {
                cell.priceLabel?.text = softInfo.drinkPrice
        }
    }

        else if indexPath.section == 1 {
        let cocktailInfo = cocktails[indexPath.row]
        cell.drinksLabel?.text = cocktailInfo.drinkName
        cell.totalLabel?.text = // how to display countValue here?

        let HappyHourStatus = partner!.barHHStatus
        if case "0" = HappyHourStatus {
            cell.priceLabel?.text = cocktailInfo.drinkHHPrice
        } else
            if case "1" = HappyHourStatus {
                cell.priceLabel?.text = cocktailInfo.drinkPrice
        }
    }
        return cell
}

and my funcs to increase or decrease the value : 和我的函数来增加或减少值:

func increaseValue(_ sender: UIButton) -> Int {

    count = 1 + count
    print(count)

    countValue = "\(count)"

    let rowToReload = IndexPath(row: sender.tag, section: sender.tag)
    let rowsToReload: [Any] = [rowToReload]
    tableView.reloadRows(at: rowsToReload as! [IndexPath], with: .automatic)

    return count
}

func decreaseValue(_ sender: UIButton) -> Int {

    if count == 0 {
        print("Count zero")
    } else {
        count = count - 1
    }

    countValue = "\(count)"

    let rowToReload = IndexPath(row: sender.tag, section: sender.tag)
    let rowsToReload: [Any] = [rowToReload]
    tableView.reloadRows(at: rowsToReload as! [IndexPath], with: .automatic)

    return count

}

I have tried countless solutions but so far none is working - thank you for your help! 我尝试了无数的解决方案,但到目前为止还没有工作 - 谢谢你的帮助!

So your problem is this code 所以你的问题是这个代码

cell.plusButton.tag = indexPath.section
cell.plusButton.tag = indexPath.row

A tag can only store one value. 标签只能存储一个值。 So you are overriding the section with the row. 因此,您将覆盖该行的部分。 So it is going to cause all sorts of weirdness. 所以它会引起各种各样的怪异。 The better solution is to determine what cell you are targeting based on the button itself. 更好的解决方案是根据按钮本身确定您要定位的单元格。 Since you know what button was clicked you can convert the location of this button to a point on the table view. 由于您知道单击了哪个按钮,因此可以将此按钮的位置转换为表视图上的某个点。 And then that point to aa particular index path. 然后指向一个特定的索引路径。

So using your example code you can do something like below: 因此,使用您的示例代码,您可以执行以下操作:

var softsCount: [Int] = []
var cocktailsCount: [Int] = []

override func viewDidLoad() {
    super.viewDidLoad()

    softsCount = Array(repeating: 0, count: softs.count) // Fill an array with 0
    cocktailsCount = Array(repeating: 0, count: cocktails.count) // Fill an array with 0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    ...
    if indexPath.section == 0 {
        ...
        cell.totalLabel?.text = "\(softsCount[indexPath.row])"
        ...
    } else if indexPath.section == 1 {
        ...
        cell.totalLabel?.text = "\(cocktailsCount[indexPath.row])"
        ...
    }
    ...
}

func increaseValue(_ sender: UIButton) {
    let pointInTable = sender.convert(sender.bounds.origin, to: tableView)
    if let indexPath = self.tableView.indexPathForRow(at: pointInTable), let cell = tableView.cellForRow(at: indexPath) {
        if indexPath.section == 0 {
            softsCount[indexPath.row] += 1
            cell.totalLabel?.text = "\(softsCount[indexPath.row])"
        } else if indexPath.section == 1 {
            cocktailsCount[indexPath.row] += 1
            cell.totalLabel?.text = "\(cocktailsCount[indexPath.row])"
        }
    }
}

No sure why you are returning count. 不知道你为什么要回来计数。 I am sure this is just a partial implementation. 我确信这只是部分实施。 But the button should take care of the entire action including updating the label with the new count. 但按钮应该处理整个操作,包括使用新计数更新标签。 You don't normally return values from button presses. 您通常不会通过按下按钮返回值。

So updated the example to update the label with the current count. 因此更新了示例以使用当前计数更新标签。 Since I am unable to see what your drinks object I made an assumption that the drinks class has a count parameter that starts at 0. This way each individual drink has a count assigned to it. 由于我无法看到你的饮料对象,我假设饮料类的计数参数从0开始。这样,每个饮品都有一个分配给它的计数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM