属性未在super.init调用中初始化

时间:2014-06-22 12:25:56

标签: uiviewcontroller uiscrollview initialization swift ios8

我的视图控制器中有以下init方法:

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.
    }

现在self.setupScrollView方法看起来像这样:

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

我得到的错误是:

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

我看过类似的帖子,没有任何运气。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

您可以将scrollView声明为可选,并在super.init调用下方移动设置方法调用。声明如下:

var scrollView : UIScrollView?

初始化:

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!)
}