How to pass a local function to another object during init?

前端 未结 3 1292
悲&欢浪女
悲&欢浪女 2021-01-29 11:09

How to pass a local function to another object during init?

I did the below, but got \'self\' captured by a closure before all members were initialized

<
3条回答
  •  被撕碎了的回忆
    2021-01-29 11:21

    First, your property drawViewWrapper seems to be useless here since you can access it later with self.rootView and second, you should use [unowned self] to avoid capturing 'self' and creating a weak reference to it instead (and then avoid a retain-cycle).

    So I would do something like this instead:

    class ContextViewController: UIHostingController {
        
        init(drawView: CustomDrawView) {
            let drawViewWrapper = ContentView(
                drawView: drawView,
                dismiss: { [unowned self] in
                    self.dismiss(animated: true)
                })
            super.init(rootView: drawViewWrapper)
        }
    
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    

    And then if you need to access it later, you can simply use self.rootView.

提交回复
热议问题