Property not initialized at super.init call

2019-06-09 07:36发布

I have the following init method in my view controller:

init(mainViewController: UIViewController, settingsViewController: UIViewController, gap: Int) {
        self.mainViewController = mainViewController
        self.settingsViewController = settingsViewController
        self.gap = gap

        self.setupScrollView() // I get error here

        super.init(nibName: nil, bundle: nil) //and here.
    }

The self.setupScrollView method for now just looks like this:

func setupScrollView() {
        self.scrollView = UIScrollView(frame: CGRectZero)
        self.scrollView.setTranslatesAutoresizingMaskIntoConstraints(false)
        self.view.addSubview(self.scrollView)
    }

The errors I get are:

self used before super.init call and Property 'self.scrollView' not initialized at super.init call

I've looked at similar post without any luck. Any help would be appreciated!

1条回答
来,给爷笑一个
2楼-- · 2019-06-09 07:58

You can do it by declaring scrollView as optional and moving the setup method call below the super.init call. The declaration would look like this:

var scrollView : UIScrollView?

And the initialisation:

init(mainViewController: UIViewController, settingsViewController: UIViewController, gap: Int) {
    //other stuff
    super.init(nibName: nil, bundle: nil)
    self.setupScrollView()
}

func setupScrollView() {
    scrollView = UIScrollView(frame: CGRectZero)
    scrollView!.setTranslatesAutoresizingMaskIntoConstraints(false)
    view.addSubview(scrollView!)
}
查看更多
登录 后发表回答