我正在尝试学习绑定并了解Swift中的MVVM方法。
我期望下面的示例能够正常工作,实际上是调用someEventHappened
,这会调用onEvent
闭包,并且我的消息会记录到屏幕上。
这不会发生,但是什么也没印出来,我不确定为什么吗?
class ViewModal {
public var onEvent: (() -> Void)?
func someEventHappened() -> Void {
onEvent?()
}
}
class ViewController: UIViewController {
lazy var viewModel: ViewModal = {
let viewModal = ViewModal()
return viewModal
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = .purple
viewModel.someEventHappened()
viewModel.onEvent = {
print("something happened")
}
}
}
答案 0 :(得分:0)
只需交换分配onEvent
并调用someEventHappened
viewModel.onEvent = {
print("something happened")
}
viewModel.someEventHappened()
这是因为您要在onEvent
内调用someEventHappened
处理程序,而在viewDidLoad
中首先要调用someEventHappened
,然后分配onEvent