如何在另一个 IB 自定义视图中使用 mouseEntered/-Exited 控制一个 IB 自定义视图

How to control one IB custom view with mouseEntered/-Exited in another IB custom view

很抱歉我的无能,但总的来说,我是 Cocoa、Swift 和 object-oriented 编程的新手。我的主要来源是 Cocoa Programming for OS X(第 5 版),以及 Apple 的行话和 Objective-C-riddled 开发者页面。但我来这里是因为我没有看到(或者没有意识到我看到了)任何能说明这个问题的东西。

我想通过另一个 IB-created 自定义视图 RightView 中的 mouseEntered/-Exited 操作更改一个 IB-created 自定义视图 LeftView 的内容。两者在同一个 window 中。我创建了一个玩具程序来尝试解决问题,但无济于事。

这是 RightView 的 class 定义(应该会更改 LeftView):

import Cocoa

class RightView: NSView {

    override func drawRect(dirtyRect: NSRect) {
        // Nothing here, for now.
    }

    override func viewDidMoveToWindow() {
        window?.acceptsMouseMovedEvents = true

        let options: NSTrackingAreaOptions =
            [.MouseEnteredAndExited, .ActiveAlways, .InVisibleRect]

        let trackingArea = NSTrackingArea(rect: NSRect(),
                                          options: options,
                                          owner: self,
                                          userInfo: nil)
        addTrackingArea(trackingArea)
    }

    override func mouseEntered(theEvent: NSEvent) {
        Swift.print("Mouse entered!")
        LeftView().showStuff(true)
    }
    override func mouseExited(theEvent: NSEvent) {
        Swift.print("Mouse exited!")
        LeftView().showStuff(false)
    }
}

这里是 LeftView 的 class 定义(应该由 RightView 更改):

import Cocoa

class LeftView: NSView {

    var value: Bool = false {
        didSet {
            needsDisplay = true
            Swift.print("didSet happened and needsDisplay was \(needsDisplay)")
        }
    }

    override func mouseUp(theEvent: NSEvent) {
        showStuff(true)
    }
    override func drawRect(dirtyRect: NSRect) {
        let backgroundColor = NSColor.blackColor()
        backgroundColor.set()
        NSBezierPath.fillRect(bounds)

        Swift.print("drawRect was called when needsDisplay was \(needsDisplay)")

        switch value {
        case true: NSColor.greenColor().set()
        case false: NSColor.redColor().set()
        }
        NSBezierPath.fillRect(NSRect(x: 40, y: 40,
            width: bounds.width - 80, height: bounds.height - 80))
    }

    func showStuff(showing: Bool) {
        Swift.print("Trying to show? \(showing)")
        value = showing
    }
}

我确定我遗漏了一些东西 "completely obvious," 但我有点笨。如果您能告诉我如何修复 code/xib 文件,我将不胜感激。如果您能解释一下与 child 交谈时的情况,我将更加感激。当我接管了这个世界(我不是无能的),我会记住你的恩情。

我想出了一个比我之前的策略简单得多的解决方法。我没有在一个自定义视图中使用 mouseEntered/-Exited 操作来尝试控制在另一个自定义视图中显示的内容,我只是将 mouseEntered/-Exited 代码放入我想要控制的视图中,然后我更改了位置rect:NSTrackingArea.

在为该方法移动代码之前,我曾尝试将 NSTrackingArea 中的 owner: 更改为 LeftView() 并仅移动 mouseEntered/-Exited 代码。这会产生很多可怕的错误消息(天真的新手在这里说话),所以我放弃了。不过,很高兴知道如何正确分配 self.

以外的所有者

无论如何,如有任何进一步的想法或见解,我们将不胜感激。