简体   繁体   English

从Nib加载NSView的多个实例

[英]Load multiple instances of a NSView from Nib

I was wondering if there was a method to create a view in a xib file and then connect its outlets to a class, so you can create multiple instances of that class and place them in the window. 我想知道是否有一种方法可以在xib文件中创建视图,然后将其出口连接到一个类,以便您可以创建该类的多个实例并将其放置在窗口中。 I have some problems, so can you help me fix my code? 我有一些问题,所以您能帮我解决我的代码吗?

Here's what I did: 这是我所做的:

Firstly I created 2 files: CustomView.xib and CustomView.swift. 首先,我创建了2个文件:CustomView.xib和CustomView.swift。 Then I designed the interface adding an NSImageView to the custom view. 然后,我设计了将NSImageView添加到自定义视图的界面。 I set the file's owner to the class name and added an outlet from the NSImageView to the class. 我将文件的所有者设置为类名,然后将NSImageView的出口添加到该类。

Then I created the following function to load the interface from the nib: 然后,我创建了以下函数以从笔尖加载接口:

func loadView() -> NSView {
    var top = NSArray()
    Bundle.main.loadNibNamed("CustomView", owner: self, topLevelObjects: &top)
    let view = top[0] as! NSView
    return view
}

And set up the class to load the interface: 并设置类以加载接口:

override init(frame: CGRect) {
    super.init(frame: frame)
    let view = loadView()
    view.frame = bounds
    addSubview(view)
}

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

So I went on creating two variables of that class and placing it on the window: 因此,我继续创建该类的两个变量并将其放在窗口中:

var x = CustomView(frame: CGRect(x: 0, y: 0, width: 600, height: 105))
var y = CustomView(frame: CGRect(x: 0, y: 105, width: 600, height: 105))

And for some reasons this code gives me a strange error. 由于某些原因,此代码给了我一个奇怪的错误。 It worked the first time, with one variable, but if I place more than one, it says it couldn't cast an NSWindow type in a NSView. 它第一次使用一个变量工作,但是如果我放置多个变量,它说它不能在NSView中强制转换NSWindow类型。

Could not cast value of type 'NSApplication' (0x7fffb5cf3ef0) to 'NSView' (0x7fffb5d04bb0). 无法将类型'NSApplication'(0x7fffb5cf3ef0)的值强制转换为'NSView'(0x7fffb5d04bb0)。

在此处输入图片说明

I think that this error is given because sometimes the first top level object is the view, and sometimes it's the window. 我认为出现此错误是因为有时第一个顶级对象是视图,有时是窗口。 So I'm getting confused. 所以我很困惑。

Obviously the error is thrown on this line: 显然,此行引发了错误:

let view = top[0] as! NSView

So what's the problem here? 那么这是什么问题呢?

(Please do not answer with cocoa touch code) (请不要回答可可触摸代码)

Use the filter function to get the NSView instance 使用filter函数获取NSView实例

func loadView() -> NSView {
    var topLevelObjects = NSArray()
    Bundle.main.loadNibNamed("CustomView", owner: self, topLevelObjects: &topLevelObjects)
    let views = (topLevelObjects as Array).filter { $0 is NSView }        
    return views[0] as! NSView
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM