gpt4 book ai didi

Xcode 8 Playground 不显示 NSView

转载 作者:行者123 更新时间:2023-12-01 11:21:13 24 4
gpt4 key购买 nike

Xcode 不会在 playground 中显示 NSView。但它显示 UIView 没有任何问题。是错误吗?

代码:

let view = NSView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.layer?.backgroundColor = NSColor.white.cgColor
PlaygroundPage.current.liveView = view

Xcode Playground 也非常慢。有什么办法可以加快 Playground 的速度吗?

最佳答案

UIViewNSView 两者的工作方式不同。您发布的代码对于 UIView 来说足够了,但对于 NSView 来说就不够了。

根据 Apple 文档 NSView :

An NSView object provides the infrastructure for drawing, printing, and handling events in an app. You typically don’t use NSView objects directly. Instead, you use objects whose classes descend from NSView or you subclass NSView yourself and override its methods to implement the behavior you need.

draw(_:) draws the NSView object. (All subclasses must implement this method, but it’s rarely invoked explicitly.)

所以,你必须继承NSView并实现draw(_:)

代码如下:

import Cocoa
import PlaygroundSupport


class view: NSView
{
override init(frame: NSRect)
{
super.init(frame: frame)
}

required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

override func draw(_ dirtyRect: NSRect)
{
NSColor.blue.setFill()
NSRectFill(self.bounds)
}
}

var v = view(frame: NSRect(x: 0, y: 0, width: 200, height: 200))

PlaygroundPage.current.liveView = v

输出:

enter image description here


在 Playground 中使用 iOS 比使用 macOS 更好,因为它很简单,而且您可以找到大量教程或答案。

关于Xcode 8 Playground 不显示 NSView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42729345/

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