Search code examples
cocoasubviewmouseup

Getting NSPoint of subview on mouseUp in NSWindow


I have an app where I am creating two subviews of the main window, the subviews are of a class called Page and on each subview I am placing another subview of a class called Ad. I am dragging the Ad classes between the Page subviews. Initially I was just resetting the Ad class view's frame, but what I really want to do is place it where the NSLeftMouseUp event occurs.

My process for doing this is to register all the Page subviews into an array as they are being created. I then made a subclass of NSWindow and assigned that class to my main window in IB. I pass the array of Page views to this class.

I think overwrite the sendEvent method, checking to see if the event is a NSLeftMouseDown, NSLeftMouseDragged or NSLeftMouseUp. The NSLeftMouseDown is to check and see if the subview clicked on is the deepest subview of the window hierarchy - window->Page class->Ad class, since I want to move ads and not pages. I loop through the array and then check the descendentOf method of the NSView (Ad) clicked to see if is a descendent of the NSView (Page) being enumerated. (Hope that made sense). I then pull it's frame as well.

In NSLeftMouseDragged I change the cursor to resemble the ad being dragged.

In NSLeftMouseUp I check to see what view we are looking to move the ad to. What I can't figure out is how to get the NSPoint for NSLeftMouseUp on that view, I can get it for the window but the x/y of that point will be way off for the receiving subview...how do I retrieve the NSPoint within the subview?

...
} else if ([e type] == NSLeftMouseUp) {

    //get which view we are going to drop the ad on
    landingView = [[self contentView] hitTest:[e locationInWindow]];

    /****ui question here for Mike:
     if the mouseup event is not on a page class, should the mouse remain the dragcursor image here or should 
     we change it back to the mouse icon and stop this process****/

    if ([[landingView className] isEqual:@"Page"]) { 

        //get ad rect
        float adX = thisAdFrame.origin.x + 10.0;
        float adY = thisAdFrame.origin.y + 20.0;

        //get nspoint of mouse up event
        NSPoint p = [e locationInWindow];

        [landingView addSubview:theSubView];
        [theSubView setFrame:NSMakeRect(p.x, p.y, thisAdFrame.size.width, thisAdFrame.size.height)];

    }

}
 ...

Solution

  • You might want to take a look at NSViews -convertPoint:fromView: and -convertPointFromBacking: Methods like these help to convert rectangles, points, etc into a different coordinate system.

    Specifying nil for fromView: will convert it from that view's window. This code will apply to you:

    NSPoint eventLocation = [theSubView convertPoint:p fromView:nil];