2011-03-01 6 views
3

그래서 NSPoint 또는 NSRect를 NSTextView에서 특정 문자의 위치와 일치 시키려고합니다. 이것은 내가 그 아주 잘 작동하지 않습니다 (지금까지 무엇을 가지고, 결과는 종류의 예측할 수없는 것 같다.NSPoint/NSRect from NSTextView

NSRange theTextRange = [[theTextView layoutManager] glyphRangeForCharacterRange:[theTextStorage editedRange] actualCharacterRange:NULL]; 
NSRect theTextRect = [[theTextView layoutManager] boundingRectForGlyphRange:theTextRange inTextContainer:[theTextView textContainer]]; 

답변

6
boundingRectForGlyphRange:inTextContainer:에 의해 반환 된 RECT 컨테이너 좌표에

가. 당신은 당신이 원하는 경우 이에 대한 조정해야

NSRange theTextRange = [[textView layoutManager] glyphRangeForCharacterRange:textRange actualCharacterRange:NULL]; 
NSRect layoutRect = [[textView layoutManager] boundingRectForGlyphRange:theTextRange inTextContainer:[textView textContainer]]; 
NSPoint containerOrigin = [textView textContainerOrigin]; 
layoutRect.origin.x += containerOrigin.x; 
layoutRect.origin.y += containerOrigin.y; 
0

당신은

#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 
NSRect

NSPoint &에 의해 마우스 다운 이벤트를 사용할 수 텍스트보기로 RECT 상대를 얻을 수