从Xib迅速获得OS X addsubview [英] OS X addsubview from xib in swift

查看:127
本文介绍了从Xib迅速获得OS X addsubview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Swift for OS X从笔尖添加一个新的子视图.

I'm trying to add a new sub view form a nib using swift for OS X.

到目前为止,我已经:

  • 创建了一个新的可可应用程序"
  • 添加了一个名为"TestSubView"的新可可类"作为带有XIB文件的NSViewController的子类

我想在应用程序加载时将此子视图添加到我的主视图中.

I want to add this subview to my main view when the application loads.

在我的ViewController(主窗口的ViewController)中.

in my ViewController ( the ViewController for the main window ) i have.

import Cocoa

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let newSubView = TestSubView();
        self.view.addSubview(newSubView.view);

    }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }


}

但是我遇到了以下错误

Failed to set (contentViewController) user defined inspected property on (NSWindow): 
-[NSNib initWithNibNamed:bundle:] could not load the nibName: temp.TestSubView in bundle (null).

我意识到我需要调整子视图的大小和位置,但我似乎无法达到目的.

I realise i will need to size and position this subview but I can't seem to get to that point.

我花了一天的大部分时间试图弄清楚这一点,因此对您的帮助将不胜感激.

I've spent the better part of a day trying to figure this one out so any help would be greatly appreciated.

推荐答案

我终于使这件事起作用了.我的新代码看起来像

I finally got this thing to work. My new code looks like

import Cocoa

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let subview = TestSubView(nibName: "TestSubView", bundle: nil)!
        self.view.addSubview(subview.view)
    }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }

}

文档的帮助下找到的此答案

有人建议,如果笔尖名称和类名称相同,则无需声明nibname:(就像我最初尝试做的那样),但是文档未提及此内容-解释了原因没用!

It was suggested that if the nib name and the class name are the same you shouldn't need to declare nibname: (as i'd tried to do originally) but the docs didn't mention this - explains why it didn't work!

为了繁荣,这与OS X Yosemite(10.10.1)上的Xcode 6.1.1配合使用

For prosperity, this worked for me with Xcode 6.1.1 on OS X Yosemite (10.10.1)

这篇关于从Xib迅速获得OS X addsubview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆