gpt4 book ai didi

xcode - 加载 View 导致程序崩溃

转载 作者:行者123 更新时间:2023-11-30 13:33:12 25 4
gpt4 key购买 nike

我仍在学习 View 的工作原理,但我发现了一个无法解决的问题......我得到了 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
}

编译器说:

fatal error: unexpectedly found nil while unwrapping an Optional value

但是GraficViewController内的按钮(IBAction)运行良好!所以我认为问题与 ScrollView 有关,但我不知道会发生什么..它已初始化..

  • 只是要提一下,GraficView(frame:frame)不是问题,因为我尝试过并且效果很好。

最佳答案

我确实相信!是你不幸的罪魁祸首:

@IBOutlet weak var scrollView: NSView!

Xcode 确实通过强制展开 (!) 为 IBOutlet 生成此条目,但它实际上应该是可选的 (?),因为您无法保证何时设置该引用。如果您有一些逻辑依赖于 scrollView 的存在,则可以通过依赖 didSet 来实现:

@IBOutlet weak var scrollView: NSView? {
didSet {
guard let sview = scrollView else {
return // because scrollView is nil for some reason
}
// do your scrollView existence dependent logic here (eg. reload content)
}
}

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

我希望这会有所帮助。

关于xcode - 加载 View 导致程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36338451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com