简体   繁体   中英

Draggable NSTextField in Cocoa

I am developing an application to print Invoices. I write the following code to make the NSTextFields Draggable and match with Invoice-fields. It Works, but when a resize the window, the NSTextField, return to initial position. What can i do?

@interface DragTextField : NSTextField <NSWindowDelegate>
@property (readwrite) NSPoint location;
@end


@implementation DragTextField
@synthesize location;

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
    }

    return self;
}

- (void)drawRect:(NSRect)dirtyRect
{
    [super drawRect:dirtyRect];

}

- (BOOL) acceptsFirstMouse:(NSEvent *)theEvent
{
    return YES;
}

- (void)mouseDown:(NSEvent *)theEvent
{
    location = [theEvent locationInWindow];
    self.location = [[self superview] convertPoint:[theEvent locationInWindow] fromView:nil];
}

- (void)mouseDragged:(NSEvent *)theEvent
{

    NSPoint newDragLocation = [[self superview] convertPoint:[theEvent locationInWindow] fromView:nil];
    NSPoint thisOrigin = [self frame].origin;
    thisOrigin.x += (-self.location.x + newDragLocation.x);
    thisOrigin.y += (-self.location.y + newDragLocation.y);
    [self setFrameOrigin:thisOrigin];
    self.location = newDragLocation;
}

- (void)mouseUp:(NSEvent *)theEvent {

    [self setNeedsDisplay:YES];
}

You have to re-position your textfield whenever the window resizes by using delegate functions.

- (void)windowDidResize:(NSNotification *)notification{ 
//Change the position of your textfield depending on the window size
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM