您可以通過NSPoint &使用鼠標按下事件的NSRect
#import <Cocoa/Cocoa.h>
@interface ClickTextView : NSView {
NSMutableArray *texts;
NSPoint currentLocation;
NSCell *cell;
}
@end
#import "ClickTextView.h"
@interface TextClip : NSObject
{
@public
NSString *text;
NSPoint location;
}
@end
@implementation TextClip @end
@implementation ClickTextView
- (void)awakeFromNib
{
texts = [NSMutableArray new];
cell = [[NSTextFieldCell alloc] initTextCell: @""];
[cell setEditable: YES];
}
- (void)drawRect:(NSRect)rect
{
NSRect frame = rect;
[[NSColor whiteColor] set];
[NSBezierPath fillRect: rect];
for (TextClip *clip in texts)
{
[cell setStringValue: clip->text];
frame.origin = clip->location;
[cell drawWithFrame: frame inView: self];
}
}
- (void)mouseDown: (NSEvent*)theEvent
{
currentLocation = [self convertPoint: [theEvent locationInWindow]
fromView: nil];
NSText *fieldEditor = [[self window] fieldEditor: YES
forObject: self];
[cell endEditing: fieldEditor];
[fieldEditor setString: @""];
[cell setStringValue: @""];
NSRect frame = {currentLocation, {400, 400}};
[cell editWithFrame: frame
inView: self
editor: fieldEditor
delegate: self
event: theEvent];
}
- (BOOL)isFlipped
{
return YES;
}
- (void)textDidEndEditing: (NSNotification*)aNotification
{
NSText *text = [aNotification object];
TextClip *clip = [[TextClip alloc] init];
clip->text = [[text string] copy];
clip->location = currentLocation;
[texts addObject: clip];
[cell endEditing: text];
[self setNeedsDisplay: YES];
}
@end