简体   繁体   English

可可中的可拖动NSTextField

[英]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. 我编写以下代码以使NSTextFields可拖动并与发票字段匹配。 It Works, but when a resize the window, the NSTextField, return to initial position. 它可以工作,但是当调整窗口大小时,NSTextField返回初始位置。 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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