为什么我的scrollView是零?

时间:2016-03-31 17:41:34

标签: xcode swift view viewcontroller fatal-error

使用第一个时,滚动视图如何可能为零:@IBAction afegeixGrafic但使用@IBAction func button时它不是'? 我得到了类GraficsBalancGlobalViewController,它是类GraficViewController

的子类
class GraficsBalancGlobalViewController: GraficViewController {
  @IBAction func afegeixGrafic(sender: NSButton) {
    addNewGrafic() // which is set on the GraficViewController
  }
}

当我执行IBAction afegeixGrafic我的程序在下面标记的行上崩溃时:

class GraficViewController: NSViewController, GraficViewDataSource {
  @IBAction func button(sender: NSButton) {
    addNewGrafic()
  }

  func addNewGrafic() {
    let frame = NSRect(x: 0, y: 0, width: self.view.bounds.width , height: self.view.bounds.width * 0.25)
    let nouGrafic = GraficView(frame: frame)
    scrollView.addSubview(nouGrafic) <---- BREAK here!
  }

  @IBOutlet weak var scrollView: NSView!
  //...more code
}

编译器说:

  

致命错误:在解包可选值时意外发现nil

GraficViewController内的按钮(IBAction)效果很好!!所以我想这个问题与scrollView有关,但我不知道它可以是什么......它被初始化了..

我也试过这个:

@IBOutlet weak var scrollView: NSView? {
  didSet {
    guard let sview = scrollView else {
      addNewGrafic()
      return // because scrollView is nil for some reason, but don't work
    }
  }
}

The call stack

enter image description here

完整代码:

class GraficsBalancGlobalViewController: GraficViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do view setup here.
}

@IBAction func afegeixGrafic(sender: NSButton) {
    //performSegueWithIdentifier("Nou Grafic", sender: nil)
    //let viewController = storyboard!.instantiateControllerWithIdentifier(identifier!) as! GraficsBalancGlobalViewController
    addNewGrafic()

}

@IBAction func eliminaGrafic(sender: NSButton) {
}

}

enter image description here

1 个答案:

答案 0 :(得分:2)

它的nil是因为你如何实例化GraficsBalancGlobalViewController。您可以使用xib或故事板进行设置,但是如果没有实例化,则会对其进行实例化。 这样做:

 let viewController = storyboard.instantiateControllerWithIdentifier(identifier) as GraficsBalancGlobalViewController

不是这个:

let viewController = GraficsBalancGlobalViewController()