swift-如何从另一个类设置UIStepper值? [英] swift - How to set UIStepper value from another class?
问题描述
我有一个tableview包含一些带有UIStepper的tableviewcell.这是tableviewcell代码:
I have a tableview contains some tableviewcell with UIStepper. This is tableviewcell code:
class ShoppingCartItemCell: UITableViewCell {
static let reuseIdentifier = "ShoppingCartItemCell"
@IBOutlet weak var itemImage: UIImageView!
@IBOutlet weak var itemNameLabel: UILabel!
@IBOutlet weak var itemProviderLabel: UILabel!
@IBOutlet weak var itemPriceLabel: UILabel!
@IBOutlet weak var itemQuantityText: UITextField!
@IBOutlet weak var quantityStepper: UIStepper!
var oldValue = 0.0
var itemName = "" {
didSet {
itemNameLabel.text = itemName
}
}
var itemProvider = "" {
didSet {
itemProviderLabel.text = itemProvider
}
}
var itemPrice = "" {
didSet {
itemPriceLabel.text = itemPrice
}
}
var itemQuantity = "" {
didSet {
itemQuantityText.text = itemQuantity
}
}
}
这是表格视图中的uistepper代码:
And this is uistepper code in tableview:
class ShoppingCartViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
@IBAction func quantityStepper(_ sender: UIStepper) {
ShoppingCartItemCell.itemQuantity = "\(Int(sender.value))"// this way is not possible...
// How to update the quantityStepper value in ShoppingCartItemCell class here
}
}
如何更新ShoppingCartViewController类中的quantityStepper值?有人会告诉我在ShoppingCartItemCell类中创建quantityStepper的@IBAction,但是我的业务逻辑必须这样做.请帮忙.谢谢大家.
How to update the quantityStepper value in ShoppingCartViewController class? Some people will tell me to create @IBAction of quantityStepper in ShoppingCartItemCell class but my business logic must to do this way. Please help. Thanks all.
推荐答案
我强烈建议在Swift 4中使用键值观察,这很容易实现
I highly recommend to use Key-Value Observation in Swift 4, it's very easy to implement
在单元格中创建一个NSKeyValueObservation
属性
In the cell create a NSKeyValueObservation
property
var observation : NSKeyValueObservation?
在cellForRowAt
中的视图控制器中,为stepper设置值并为标签添加观察者
In the view controller in cellForRowAt
set the values for stepper and label add the observer
let item = dataSource[indexPath.row] // assuming `dataSource` is the data source array
cell.quantityStepper.value = item.quantity
cell.itemQuantityText.text = "\(item.quantity)"
cell.observation = cell.quantityStepper.observe(\.value, options: [.new]) { (stepper, change) in
cell.itemQuantityText.text = "\(change.newValue!)"
// update the data model for example
item.quantity = change.newValue!
}
最后,在单元格离开屏幕后,您必须在didEndDisplaying
中删除观察者.
Finally you have to remove the observer in didEndDisplaying
after the cell has left the screen.
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
(cell as! ShoppingCartItemCell).observation = nil
}
否IBAction
,没有协议/委托.这是非常简单和高效的.
No IBAction
, no protocol / delegate. It's very simple and efficient.
这篇关于swift-如何从另一个类设置UIStepper值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!