Cocoa中可拖动的NSTextField

时间:2012-11-02 13:41:52

标签: cocoa nstextfield

我正在开发一个打印发票的应用程序。我编写以下代码以使NSTextFields可拖动并与Invoice-fields匹配。它工作正常,但是当调整窗口大小时,NSTextField会返回初始位置。我该怎么办?

@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];
}

1 个答案:

答案 0 :(得分:-1)

每当窗口调整大小时,您必须使用委托函数重新定位文本字段。

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