Swift 委派 - 在 Tableview 单元格中使用步进器单独更新标签 Class

Swift Delegation - Use Stepper in Tableview Cell to Update Label in Separate Class

我经常查看 Whosebug 并阅读了很多与授权相关的不同问题,但我还没有解决我的问题。我试图让我的 stepperAction(位于 tableview 单元格内)在每次单击时更改我的 BuyStats class 中的标签。但到目前为止,点击步进器没有任何效果。我想我需要 BuyStats.viewDidLoad() 中的一些东西来以某种方式设置委托,但我没有得到它。这对某些人来说可能很容易。谢谢你的帮助。

protocol SetRemainingValue : class {
func setValue(amount: Double)
}
}

//

class BuyStatsCell: UITableViewCell{

weak var setRemaining : SetRemainingValue?

@IBAction func stepperAction(_ sender: UIStepper) {

    setRemaining?.setValue(amount: sender.value)
}

//

class BuyStats: UIViewController, SetRemainingValue {

   @IBOutlet weak var spendAmount: UILabel!

override func viewDidLoad(){

}

 func setValue(amount: Double) {

    spendAmount.text = amount

}

}

如果您使用的是动态 UITableView,您可以在 cellForRowAtIndexPath 中尝试以下操作:

  1. 当您使用 dequeueCellWithReuseIdentifier 初始化单元格时,将其转换为 BuyStatsCell(可能使用 as! BuyStatsCell)以访问其 class 变量。
  2. cell.setRemaining = self 设置委派。 self 的使用假定您的 tableView 的 cellForRowAtIndexPathBuyStats viewController class 内。如果不是,您可能希望在 tableView 代码所在的 class 中获取 BuyStats 对象的引用,并使用该引用代替 self,例如 cell.setRemaining = /*yourBuyStatsObjectReferenceGoesHere*/.

希望对您有所帮助。