NSImageView mouseDragged Значение передается обратно в windowController

Может кто-нибудь показать мне, как вернуть позиции X и Y обратно в мой WindowController NSTextField (testTextX и testTextY)?

Я создал windowController, NSImage и NSTextField программно. Я добавил изображение "точка" в NSView и хотел бы, чтобы изображение "точка" перетаскивалось и возвращало позиции X и Y.

Мне удается добавить и перетащить изображение, но я не знаю, как я могу передать позиции X и Y на mouseDragged обратно в NSTextField на моем WindowController (testTextX и testTextY)?

Текущее отображение, как показано ниже, при нажатии на "точечное" изображение, оно перетаскивается в любую позицию.

Я могу распечатать позиции X и Y из NSImageView func mouseDragged(theEvent: NSEvent) когда изображение было перетащено.

Я застрял в том, как передать позиции X и Y обратно в WindowController.

Мой код WindowController.swift, как показано ниже:

public class MyWindowController: NSWindowController, NSWindowDelegate {
    // MARK: Constants
    // 1. Define min&max window size
    var fWidth:CGFloat = 0
    var fHeight:CGFloat = 0
    var vWidth:CGFloat = 0
    var vHeight:CGFloat = 0
    var blankPage: NSView!

    var viewDotImg: NSImageView!
    var testTextX: NSTextField!
    var testTextY: NSTextField!

    var modalWinHeight: CGFloat = 0
    var m_window:NSWindow = NSWindow()

    // MARK: Initializer
    init(){
        super.init(window: self.m_window)
    }

    init(channelId:Int){
        super.init(window:self.m_window)

        // Get the window full width and height
        fWidth = (NSScreen.mainScreen()?.frame.width)!
        fHeight = (NSScreen.mainScreen()?.frame.height)!

        // Get the window visible width and height
        vWidth = (NSScreen.mainScreen()?.visibleFrame.width)!
        vHeight = (NSScreen.mainScreen()?.visibleFrame.height)!

        // Get the position X and Y for Window
        let winPosX: CGFloat = fWidth - vWidth
        let winPosY: CGFloat = fHeight - vHeight

        // Divide the height by 3
        let avgHeight: CGFloat = vHeight / 3

        // Set the max window height as avgHeight * 1.3
        let modalWinHeight: CGFloat = avgHeight * 1.3

        // Set the window frame
        self.m_window = NSWindow(contentRect: NSMakeRect(winPosX, winPosY, vWidth, modalWinHeight),
            styleMask: NSClosableWindowMask | NSMiniaturizableWindowMask | NSTitledWindowMask,
            backing: NSBackingStoreType.Buffered, `defer`: false);

        // Window delegate
        self.m_window.delegate = self

        // Add a blank NSView with Gradian background colour
        blankPage = CGradiantBlank(x: x, y:y, width:width, height: height)
        self.window?.contentView = blankPage

        // Add Image Dot to NSView
        viewDotImg = DragNSImageView(x: 200, y: 200, width: 10, height: 10)

        // Add Two TextField to NSView
        testTextX = TextLabel(x: 200, y: 10, width: 100, height: 24, value: "100")
        testTextY = TextLabel(x: 305, y: 10, width: 100, height: 24, value: "100")

        blankPage.addSubview(viewDotImg)
        blankPage.addSubview(testTextX)
        blankPage.addSubview(testTextY)
    }

    func updTestXY(x:Double, y:Double){
        testTextX.stringValue = String(x)
        testTextY.stringValue = String(y)
    }

    override public init(window: NSWindow?) {
        super.init(window: window)
    }

    required public init?(coder:NSCoder){
        super.init(coder: coder)
    }    
}

Мой код NSImageView, как показано ниже:

public class DragNSImageView: NSImageView {
    private var xWidth: CGFloat = 0
    private var xHeight: CGFloat = 0

    init(x:CGFloat, y:CGFloat, width:CGFloat, height:CGFloat, chId: Int) {
        super.init(frame: NSRect(x: x,y: y,width: width,height: height))
        super.imageScaling = NSImageScaling.ScaleAxesIndependently
        super.image = NSImage(named: "dot-10")
        xWidth = width
        xHeight = height
    }

    required public init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override public func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)
    }

    public override func mouseDragged(theEvent: NSEvent) {
        super.mouseDown(theEvent)
        let location = theEvent.locationInWindow
        let pX: CGFloat = location.x
        let pY: CGFloat = location.y
        super.frame = NSRect(x: pX,y: pY,width: xWidth,height: xHeight)
        Swift.print("X: \(location.x)" Y: \(location.y))
        /* How to pass this location.x and location.y back to WindowController func updateTestXY()? 

        updTestXY(Double(location.x), y:Double(location.y))
        */
    }
}

Мой код NSTextField, как показано ниже:

public class TextLabel: NSTextField {
    // MARK: Initializer
    init(){
        super.init(frame: NSRect(x: 0, y: 0, width: 90, height: 10))
    }

    convenience init(x:CGFloat, y:CGFloat, width:CGFloat, height:CGFloat, value:String){
        self.init()
        super.wantsLayer = true
        super.backgroundColor = NSColor.darkGrayColor()
        super.textColor = NSColor.whiteColor()
        super.stringValue = value
        super.frame = NSRect(x: x, y: y, width: width, height: height)
    }

    required public init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override public func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)
    }
}

1 ответ

Хорошо, я нашел решение.

let mainWindow = self.window?.windowController as! MyWindowController
mainWindow.updXY(location.x, y:location.y, refName: refName)

Если более одного "точечного" изображения, то добавьте следующий код в init NSImageView ()

super.identifier = "ReferenceName1"

Теперь перейдите к NSImageView mouseDragged(theEvent: NSEvent) метод и добавьте следующую строку:

let refName = super.identifier

Это будет использоваться в MyWindowController для определения того, какое "точечное" изображение было перетащено при вызове указанной функции. В моем случае я называю

updXY(location.x, y:location.y, refName: refName)

Итак, в MyWindowController я использую следующее, чтобы сделать работу.

public func updXy(x: CGFloat, y: CGFloat, refName: String){
    if refName == "ReferenceName1" {

    }else if refName == "ReferenceName2" {

    }
}
Другие вопросы по тегам