gpt4 book ai didi

swift - 如何在 Playgrounds 中将 VC 设置为 Liveview?

转载 作者:搜寻专家 更新时间:2023-11-01 06:55:10 25 4
gpt4 key购买 nike

我目前正在开发一个小型 Playgrounds 项目(适用于 macOS),我正在尝试将我自己的 View Controller 设置为实时 View 。以下行不起作用。

PlaygroundPage.current.liveView = ViewController()

运行它时,出现以下错误。

error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

我得到同样的错误,当使用这个:

PlaygroundPage.current.liveView = ViewController(nibName: NSNib.Name("MyView"), bundle: Bundle.main)

最佳答案

选择"file">“新建”>“ Playground ”,然后从名为“单一 View ”的 MacOS Playground 模板开始。这将为您提供 Nib View 。

现在修改playground中的代码如下:

import AppKit
import PlaygroundSupport

class ViewController : NSViewController {}

let nibFile = NSNib.Name("MyView")
var topLevelObjects : NSArray?

Bundle.main.loadNibNamed(nibFile, owner:nil, topLevelObjects: &topLevelObjects)
let views = (topLevelObjects as! Array<Any>).filter { $0 is NSView }

let vc = ViewController()
vc.view = views[0] as! NSView
PlaygroundPage.current.liveView = vc

运行 playground 并查看 Assistant Editor Pane 。你会看到这个:

enter image description here


编辑 在我看来,一种更愉快的写法(将在何处获取其 View 的决定权交由 View Controller 本身决定)如下所示:

class ViewController : NSViewController {
override func loadView() {
let nibFile = NSNib.Name("MyView")
var topLevelObjects : NSArray?
Bundle.main.loadNibNamed(
nibFile, owner:nil, topLevelObjects: &topLevelObjects)
let views = (topLevelObjects as! Array<Any>).filter { $0 is NSView }
self.view = views[0] as! NSView
}
}
PlaygroundPage.current.liveView = ViewController()

关于swift - 如何在 Playgrounds 中将 VC 设置为 Liveview?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53950505/

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