使用archivedDataWithRootObject / unarchiveObjectWithData复制NSView

时间:2016-05-23 02:52:16

标签: swift macos cocoa

我正在尝试复制NSView,然后将其添加到同一个superview。我在Stackoverflow上发现了一些使用archivedDataWithRootObject / unarchiveObjectWithData方法的代码,但是我仍然遗漏了一些东西,因为当添加了addSubview时,未归档的NSView没有显示。

enter image description here

以下是Interface Builder中的设置。在ViewController中有一个名为customView的带有引用插座的NSView。它有两个NSView子视图。我将他们的身份设置为“一个”和“两个。并扩展NSView类,以便可以通过身份找到它们。我正在尝试复制第二个NSView,然后将其添加到同一个父NSView,但它不会出现。” / p>

以下是代码:

import Cocoa

class ViewController: NSViewController {
  @IBOutlet var customView: NSView!

  override func viewDidLoad() {
    super.viewDidLoad()
    let v = customView.viewWithID("two")

    // create an NSData object from myView
    let archive = NSKeyedArchiver.archivedDataWithRootObject(v!)

    // create a clone by unarchiving the NSData
    let myViewCopy = NSKeyedUnarchiver.unarchiveObjectWithData(archive) as! NSView

    // I am setting the background color to make it visible
    myViewCopy.backgroundColor = NSColor.redColor()

    // adding it
    customView.addSubview(myViewCopy)
    // .. and nothing happens!
    // so I tried to specify origin, to make sure it's not outside the visible area
    myViewCopy.frame.origin.x = 0
    myViewCopy.frame.origin.y = 0
    // .. still no effect
  }
}

extension NSView {
var backgroundColor: NSColor? {
    get {
        if let colorRef = self.layer?.backgroundColor {
            return NSColor(CGColor: colorRef)
        } else {
            return nil
        }
    }
    set {
        self.wantsLayer = true
        self.layer?.backgroundColor = newValue?.CGColor
    }
}

func viewWithID(id:String) -> NSView? {
    for view in subviews {
        if let identifier = view.identifier {
            if identifier == id {
                return view
            }
        }
    }
    return nil
  }
}

enter image description here

我错过了什么?

0 个答案:

没有答案