【问题标题】:how can I change value of label constantly如何不断更改标签的值
【发布时间】:2017-07-22 10:29:38
【问题描述】:

我在视图控制器中有一个标签和表格视图,如下所示:

我希望当用户点击 tableViewCell 上的步进按钮时,上部标签(green 按钮下方的数字)得到更新。但是我无法从我的单元格中访问标签。

有什么建议吗? 编辑: 这是我的 tablevc 代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "basket", for: indexPath) as! basketcell2
    cell.ConfigureCell(number: basket[basketfoodtitle[indexPath.row]]!, price: foodtitleprice[basketfoodtitle[indexPath.row]]!, foodtitle: basketfoodtitle[indexPath.row])

    return cell
}

这是我的手机密码:

@IBAction func steperchanged(_ sender: Any) {
    NumberOfFood.text = String(Int(stepper.value))
    let totalprice = Int(stepper.value)*foodtitleprice[foodtitle.text!]!
    TotalPrice.text = totalprice.stringFormatedWithSepator

}
func ConfigureCell(number:Int,price:Int,foodtitle:String)  {
        stepper.value = Double(number)
        Price.text = price.stringFormatedWithSepator
        NumberOfFood.text = String(number)
        self.foodtitle.text = foodtitle
        let totalprice = Int(stepper.value) * foodtitleprice[foodtitle]!
        TotalPrice.text = totalprice.stringFormatedWithSepator
    }

【问题讨论】:

  • 选项有:委托、VC的静态方法、通知中心等
  • 这个答案可以帮到你:stackoverflow.com/questions/41363854/…
  • 你让我觉得很想吃披萨 :D
  • 关于 RinaLui 所说的:我建议你看this 的答案。最终,您必须学习如何使用委托。尝试应用该答案,然后显示一些代码,如果它不适合您,请粘贴 您的代码 并获得进一步的帮助
  • @Honey 我看到了委托解决方案,但它是用于在 vc 之间传递数据的矿井来自一个 vc :( 你能写出这个案例的委托解决方案吗?

标签: swift xcode uitableview tableview


【解决方案1】:

最好的方法是通过使用委托,但如果那不可能,请检查下面的代码,这是最简单的

var counterForTopLabel : Int = Int(){
  didSet{
    self.counterLabel.text = "\(counterForTopLabel)";
  }
}

在你的 cellForRowAtIndexPath 中你可以为按钮添加目标

cell.incrementCounterButton.addTarget(self, action: #selector(self.tappedIncrementButton(sender:)), for: .touchUpInside);
cell.decrementCounterButton.addTarget(self, action: #selector(self.tappedDecrementButton(sender:)), for: .touchUpInside);

那么这些函数将在下面声明

func tappedIncrementButton(sender : UIButton){
    counterForTopLabel = counterForTopLabel + 1;
}
func tappedDecrementButton(sender : UIButton){
    counterForTopLabel = counterForTopLabel - 1;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-15
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多