在MainVC.swift
我正在捕捉自定义" PlayerCell
"的标记。我想按increaseBtn
(UIButton
),这会将playerLbl.text
(UILabel
)增加1,但也会更新我的模型(PlayerStore.player.playerScore: Int)
Main.swift:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "PlayerCell", for: indexPath) as? PlayerCell {
let player = players[indexPath.row]
cell.updateUI(player: player)
cell.increaseBtn.tag = indexPath.row
cell.decreaseBtn.tag = indexPath.row
return cell
} else {
return UITableViewCell()
}
}
PlayerCell.swift
class PlayerCell:UITableViewCell {
@IBOutlet weak var playerLbl: UILabel!
@IBOutlet weak var increaseBtn: UIButton!
@IBOutlet weak var decreaseBtn: UIButton!
@IBOutlet weak var scoreLbl: UILabel!
@IBOutlet weak var cellContentView: UIView!
func updateUI(player: Player){
playerLbl.text = player.playerName
scoreLbl.text = "\(player.playerScore)"
cellContentView.backgroundColor = player.playerColor.color
}
@IBAction func increaseBtnPressed(_ sender: AnyObject) {
let tag = sender.tag
// TODO: send this tag back to MainVC?
}
答案 0 :(得分:1)
在这种情况下我会使用委托模式。创建Main.swift实现的协议,并且PlayerCell.swift用作可选属性。例如:
protocol PlayerIncrementor {
func increment(by: Int)
func decrement(by: Int)
}
然后在Main.swift上使用扩展来实现此协议
extension Main: PlayerIncrementor {
func increment(by: int) {
//not 100% what you wanted to do with the value here, but this is where you would do something - in this case incrementing what was identified as your model
PlayerStore.player.playerScore += by
}
}
在PlayerCell.swift内部,添加一个委托属性并在@IBAction
class PlayerCell: UITableViewCell {
var delegate: PlayerIncrementor?
@IBOutlet weak var increaseBtn: UIButton!
@IBAction func increaseBtnPressed(_ sender: AnyObject) {
let tag = sender.tag
//call the delegate method with the amount you want to increment
delegate?.increment(by: tag)
}
最后 - 要使一切正常,请将Main指定为PlayerCell UITableViewCell.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "PlayerCell", for: indexPath) as? PlayerCell {
//self, in this case is Main - which now implements PlayerIncrementor
cell.delegate = self
//etc