【发布时间】:2021-05-31 05:41:00
【问题描述】:
我有两个视图控制器(ViewController 和 ActionViewController)和一个管理器(Brain),第二个视图控制器在用户访问时显示通过在情节提要中创建的显示转场点击按钮并返回第一个,我在第二个视图控制器中使用了 self.dismiss。
用户在 ActionViewController 上输入一个数字,需要在 ViewController 中检索。所以我创建了 Brain 来使用委托模式。
问题是 ViewController 中的委托函数从未运行,我阅读了其他 SO 答案,但没有任何效果。我使用 print 语句来知道代码不再运行的位置,唯一没有运行的块是 ViewController
中的 didUpdatePrice这里是代码
视图控制器
class ViewController: UIViewController, BrainDelegate {
var brain = Brain()
@IBOutlet var scoreLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
brain.delegate = self
scoreLabel.layer.cornerRadius = 25
scoreLabel.layer.masksToBounds = true
}
func didUpdateScore(newScore: String) {
print("the new label is \(newScore)")
scoreLabel.text = newScore
}
}
ActionViewController
class ActionViewController: UIViewController {
var brain = Brain()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func addButtonTapped(_ sender: Any) {
brain.newAction(actualScore: 0, newActionValue: 5, isPositive: true)
self.dismiss(animated: true)
}
}
大脑
protocol BrainDelegate {
func didUpdateScore(newScore: String)
}
struct Brain {
var delegate: BrainDelegate?
func newAction(actualScore: Int, newActionValue: Int, isPositive: Bool) {
let newScore: Int
if isPositive {
newScore = actualScore + newActionValue
} else {
newScore = actualScore - newActionValue
}
print("the new score is \(newScore)")
delegate?.didUpdateScore(newScore: String(newScore))
}
}
【问题讨论】:
标签: ios swift delegates swift-protocols