我正在尝试学习绑定并了解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")
        }
    }
}

最佳答案

只需交换分配onEvent并调用someEventHappened

viewModel.onEvent = {
    print("something happened")
}
viewModel.someEventHappened()


这是因为您要在onEvent中调用someEventHappened处理程序,而在viewDidLoad中您首先调用了someEventHappened,然后分配了onEvent

10-08 15:42